Consecutive Value Printing in for-Loops Using setTimeout
Issue:
In the following script, the setTimeout function is used within a for loop to alert values sequentially. However, the resulting output shows that the value '3' is printed twice instead of '1' and '2' as expected.
for (var i = 1; i <= 2; i++) { setTimeout(function() { alert(i) }, 100); }
Reason:
The problem arises because the value of i in the for loop is modified over time, but the setTimeout function captures only a reference to the original variable.
Solution:
To address this issue, the i variable should be captured as a unique value for each timeout function. This can be achieved by creating a new function that takes i as an argument and then calls setTimeout with this argument:
function doSetTimeout(i) { setTimeout(function() { alert(i); }, 100); } for (var i = 1; i <= 2; ++i) doSetTimeout(i);
With this approach, each iteration of the loop creates a distinct copy of the i variable, ensuring that the alerted values are printed consecutively as expected.
The above is the detailed content of Why Does `setTimeout` in a `for` Loop Print Unexpected Values, and How Can This Be Fixed?. For more information, please follow other related articles on the PHP Chinese website!