Home > Web Front-end > JS Tutorial > Why Does Nested `setTimeout` in a JavaScript `for` Loop Print Non-Consecutive Values?

Why Does Nested `setTimeout` in a JavaScript `for` Loop Print Non-Consecutive Values?

Mary-Kate Olsen
Release: 2024-12-15 15:32:14
Original
852 people have browsed it

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template