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.

2
  • You do increase it. If you didn't, they would all be logged at the same time. Commented Feb 13, 2020 at 10:37
  • You simulate a setInterval Commented Feb 13, 2020 at 10:40

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This is perfect! Can you please explain why this works?
yup, let me add the explanation in the answer
@pavanskipo After you added an explanation, please remove the horizontal scollbar.
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.

2 Comments

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..
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.