osiris355 osiris355 - 13 days ago 4
AngularJS Question

$timeout inside will loop creates infinite loop

I cannot seem to get the timeout and the loop to work together. If I remove the loop it works or if I remove the timeout it will work. Together I will get an infinit loop and it doesnt seem like the timeout function ever runs if its inside of the while loop.

Any help would be appreciated!

function doTask (list) {
if (list) {
while (list.length > 0) {
(function(list){
$timeout(function() {
list.splice(0, 1);
console.log("timeout...")
}, 5000);
})(list);
}
}
}

Answer

You should use recursion to loop. Also, you should check list.length as [] is a true value.

function doTask(list) {
  if (list.length) {
    setTimeout(function() {
      list.splice(0, 1);
      console.log("timeout...")
      doTask(list);
    }, 500);
  }
}
var list = [1,2,3,4,5]
doTask(list);