Understanding setTimeout in JavaScript Loops
Let's explore how setTimeout()
behaves inside JavaScript loops using two different examples.
Example 1: Using var
keyword
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1);
}
This code snippet creates a loop using the var
keyword to declare the variable i
. Inside the loop, a setTimeout()
function is called with an arrow function as its argument, which logs the current value of i
after a timeout of 1 millisecond.
What do you think the output of this code would be?
The output would be:
3
3
3
This happens because when the callback function inside setTimeout()
is executed, the loop has already finished executing, and the final value of i
is 3.
Example 2: Using let
keyword
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1);
}
In this code snippet, the loop uses the let
keyword to declare the variable i
. Inside the loop, a setTimeout()
function is again called with an arrow function that logs the current value of i
after a timeout of 1 millisecond.
What do you think the output of this code would be?
The output would be:
0
1
2
Unlike the first example, here each iteration of the loop has its own lexical environment due to the block-scoping behavior of let
. So, each invocation of the arrow function captures the value of i
at that particular iteration.
This demonstrates how using var
and let
keywords can produce different results when dealing with asynchronous operations like setTimeout()
inside loops in JavaScript.