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

 function slowDown () {
   time = setTimeout(function (){
       do something else
   }, 5000);
};
fortunee
  • 3,852
  • 2
  • 17
  • 29
Kolu99
  • 5
  • 2
  • What is the expected behavior? – Nicholas Tower Jul 19 '21 at 16:38
  • `slowDown()` will schedule something to execute *later*. It will not actually slow down anything. If you have a loop over 10 items, then you'd just have 10 tasks scheduled to execute 5 seconds later. – VLAZ Jul 19 '21 at 16:40
  • If I try it the other way around, the length of the array is undefined – Kolu99 Jul 19 '21 at 16:45
  • You can await a promise instead: https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep – ArchKudo Jul 19 '21 at 17:06

2 Answers2

0

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);
Kinglish
  • 23,358
  • 3
  • 22
  • 43
-1

What @vlaz has pointed out in the comment to the question is correct:

slowDown() will schedule something to execute later. It will not actually slow down anything. If you have a loop over 10 items, then you'd just have 10 tasks scheduled to execute 5 seconds later.

Not sure if this might help, but I think this is quite similar https://stackoverflow.com/a/5226333/10293708

Ankit Gupta
  • 175
  • 6