setTimeout in a for loop

setTimeout in a for loop

Ferenc Almasi β€’ 2020 December 11 β€’ Read time 1 min read
  • twitter
  • facebook
JavaScript

Do you know what happens in JavaScript, if you put a setTimeout into a for loop?

Copied to clipboard!
or (var i = 0; i < 3; i++) {
    setTimeout(() => console.log(i), 0);
}
setTimeout.js

It will output 3, three times in a row. This is because setTimeout is a browser API that is deferred to the end of the call stack. By the time the callback function is returned to the call stack, the value of i will already be 3. To get the desired behavior, you could use a let instead:

Copied to clipboard!
for (let i = 0; i < 3; i++) {
    setTimeout(() => console.log(i), 0);
}
setTimeout.js
What is the output of the following code?
If you would like to see more Webtips, follow @flowforfrank

50 JavaScript Interview Questions

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.