Home >Web Front-end >JS Tutorial >Why Does This JavaScript Loop Produce Unexpected Results with `setTimeout`?

Why Does This JavaScript Loop Produce Unexpected Results with `setTimeout`?

DDD
DDDOriginal
2024-12-15 20:37:10126browse

Why Does This JavaScript Loop Produce Unexpected Results with `setTimeout`?

Asynchronous Execution of Loops and setTimeout

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.

Understanding the JavaScript 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.

The Issue with the Loop

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.

The Correct Approach

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn