0

So I'm trying to increase the time out in a for loop, I followed the answer here setTimeout with Loop in JavaScript but the duration of the setTimeout is just not working in milliseconds when I output the date to check the time difference.

Code:

for (var count = 0; count < 12; count++) {
    (function(num){setTimeout(function() {
        console.log("Count = " + num + " Time: " + 1000 * num + " Stamp: " + new Date());
    }, 1000 * num)})(count);
}

As you can see in the console, it's still firing the console.log every 1000 instead of 1000 * count.

I hope the above makes sense and hopefully someone can explain this behaviour.

designtocode
  • 2,215
  • 4
  • 21
  • 35

2 Answers2

2

The code is working as expected.

All the timers are all set almost at the same time as they are async. So, the timers are set and the code continues loading the other timers without waiting for the code to be executed.

The first timer will go off after 1 second.

The second timer will go off after 2 seconds. But two seconds after the timer was set, which is the same time at which the timer 1 was set.

And so on.

So, each timer is firing at 1000 * count.

Buddy Christ
  • 1,364
  • 8
  • 22
  • This is great thanks for explaining. But how do I get this to work the way I want after each iteration? Meaning how do I fire the timeout in milliseconds from the previous iteration.. – designtocode Feb 13 '20 at 10:45
  • instead of setting all the timers at the same time set them at the callback which is the code that will be fired when the time has passed – Buddy Christ Feb 13 '20 at 10:47
2

Is this what you are looking for? Increase the time for each iteration 1second * some count

let i = 0;
loop = () => {
  setTimeout(() => {
    console.log("Count = " + i + " Time: " + 1000 * i);
    i++;
    if (i < 10) {
      loop();
    }
  }, i * 1000)
};
loop();

Here is a REPL, you can hit run

Explanation: Try running this code

for (var i = 1; i < 5; i++) {
    setTimeout(() => console.log(i), 1000)
} 

We would expect the output to be 1 2 3 4 but its actually 5 5 5 5, that's because js runtime engine does not wait for the settimeout to complete instead it passes it onto the web API and it is queued there, so the for loop executes first making i = 5 and at a later point of time the Web API's triggers the set time out function. You can learn about this in detail here.

Pavan Skipo
  • 1,757
  • 12
  • 29