Home > Web Front-end > JS Tutorial > Why Does `setTimeout` in a `for` Loop Print Unexpected Values, and How Can This Be Fixed?

Why Does `setTimeout` in a `for` Loop Print Unexpected Values, and How Can This Be Fixed?

Barbara Streisand
Release: 2024-12-15 21:13:11
Original
613 people have browsed it

Why Does `setTimeout` in a `for` Loop Print Unexpected Values, and How Can This Be Fixed?

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

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

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!

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