Consider the following script:
for (var i = 1; i <= 2; i++) { setTimeout(function () { alert(i) }, 100); }
As opposed to the expected values of 1 and 2, the script outputs 3 twice. This behavior arises due to the asynchronous nature of JavaScript's event loop.
JavaScript's event loop processes code execution in two stages: a synchronous stack and an asynchronous queue. Synchronous code executes immediately in the stack, while asynchronous code, such as setTimeouts, is placed in the queue to be executed later.
In the script, the setTimeout callback function uses the variable i. However, i is shared between all iterations of the loop, and by the time the callback executes, it always refers to the final value of 2. Hence, 3 is printed both times.
To ensure consecutive values are printed, create a distinct copy of i for each callback function. This can be achieved using a function closure, as shown below:
function doSetTimeout(i) { setTimeout(function () { alert(i); }, 100); } for (var i = 1; i <= 2; ++i) doSetTimeout(i);
In this script, the doSetTimeout function captures the value of i as a local variable for its closure, ensuring that each callback function uses the correct value.
The above is the detailed content of Why Does This JavaScript Loop Produce Unexpected Results with `setTimeout`?. For more information, please follow other related articles on the PHP Chinese website!