setTimeout in a for loop
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);
}
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);
}
Resources:
π More Webtips
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: