0

for (let i = 0; i < 5; i++) {
  setTimeout(function() {
    console.log(i);
  }, i * 1000);
}

In the above mentioned code, we are getting 0,1,2,3,4 as output with the time period of 1 seconds. As we are giving time interval as i*1000, then why time interval is not increasing. I mean inside the loop when i value is 3 or 4 time interval would be 3 seconds or 4 seconds. It should keep on increasing as it depends on i. I am having small idea about event loop and callback queue. But I couldn't able to relate it here. Please explain.

2
  • It is increasing. The code causes 4 functions to be called in 1000, 2000, 3000 and 4000 ms from when the code runs. The relative duration between the function calls is always ~1000 ms Commented Dec 30, 2019 at 12:23
  • setTimeout() doesn't halt the execution of the loop. Commented Dec 30, 2019 at 12:24

2 Answers 2

1

The code is working correctly. This is what your code does. It says that the function should be called in 1*1000 mlliseconds, then in 2*1000 milliseconds, then in 3*1000 milliseconds and so on.

So when 1 second has elapsed, the function will be called for the first time. When 2 seconds have elapsed, the function will be called for the second time. When 3 seconds have elapsed, the function will be called for the third time. And so on.

So that's why, when the program runs, you're observing that the function is being called in 1 second intervals.

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

Comments

1

The code works fine, javascript runs asynchronous. That means setTimeout() dont block the code.It just executes your setTimeout and continue its loop. The code is almost equivalent to this code here:

<script>

setTimeout(function(){
   console.log(0 + " seconds");
}, 0 * 1000)

setTimeout(function(){
   console.log(1 + " seconds");
},1 * 1000)

setTimeout(function(){
   console.log(2 + " seconds");
},2 * 1000)

setTimeout(function(){
   console.log(3 + " seconds");
},3 * 1000)

setTimeout(function(){
   console.log(4 + " seconds");
},4 * 1000)

</script>

1 Comment

"javascript runs asynchronous" seems too vague. JavaScript is very much synchronous, but an event loop exists and some operations add new tasks to that loop. setTimeout being one of them.

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.