Home >Web Front-end >JS Tutorial >Why Does Nested `setTimeout` in a JavaScript `for` Loop Print Non-Consecutive Values?
Understanding the Issue: Non-Consecutive Value Printing in setTimeout Nested in for-Loop
In JavaScript, asynchronous functions like setTimeout schedule a callback to execute after a delay. When placed within a loop, this can lead to unexpected behavior where the variables accessed by the callback may be out of sync with the loop's state.
The Example: Alerting Incorrect Values
Consider the provided script:
for (var i = 1; i <= 2; i++) { setTimeout(function() { alert(i) }, 100); }
This code intends to alert the values 1 and 2 consecutively, but instead outputs 3 twice. The reason lies in the asynchronous nature of setTimeout, which creates a callback that reference the current value of i.
Passing i Without a Function String
To address this issue and ensure consecutive value printing, we need to create a distinct instance of i for each setTimeout callback. Here's a solution:
function doSetTimeout(i) { setTimeout(function() { alert(i); }, 100); } for (var i = 1; i <= 2; ++i) doSetTimeout(i);
By creating an explicit function for each callback and passing i as an argument, we create separate copies of i for each iteration of the loop. This allows the callbacks to reference the correct value of i when executed, ensuring the consecutive printing of 1 and 2.
The above is the detailed content of Why Does Nested `setTimeout` in a JavaScript `for` Loop Print Non-Consecutive Values?. For more information, please follow other related articles on the PHP Chinese website!