Search code examples
javascriptfor-loopsettimeout

setTimeout not working inside of my for loop - skipping it completely


function whatever () {
  for (var i=0; i < arr.length; i++) {
     do something
    slowDown();
  };
};

 function slowDown () {
   time = setTimeout(function (){
       do something else
   }, 5000);
};

Solution

  • Rather than that, why not just set and interval, execute on the current array value until it's done, then clear it?

    let ctr = 0, time = setInterval(function() {
        let curitem = arr[ctr];
        // do somethign with curitem
        if (++ctr >= arr.length) clearInterval(time)
      }, 5000);