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
Release: 2024-12-15 20:37:10
Original
125 people have browsed it

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);
}
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template