Home >Web Front-end >JS Tutorial >Why Does `setTimeout` in a `for`-Loop Print the Last Value Twice, and How Can I Fix It?

Why Does `setTimeout` in a `for`-Loop Print the Last Value Twice, and How Can I Fix It?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-03 22:50:40707browse

Why Does `setTimeout` in a `for`-Loop Print the Last Value Twice, and How Can I Fix It?

Consecutive Value Output with setTimeout in for-Loop

You're encountering an issue where you're attempting to print consecutive values using setTimeout within a for-loop, but it's resulting in the last value being printed twice. This occurs because when you use the variable i directly within the setTimeout function, its value is updated by the time the function executes. To resolve this, it's essential to create a distinct copy of i for each iteration.

The provided solution achieves this by declaring a helper function called doSetTimeout. In this function, a new variable is declared to hold the current value of i, which is then passed as an argument when creating the timeout. This ensures that each timeout function has its own distinct copy of i, eliminating any issues with value updates during execution.

function doSetTimeout(i) {
  setTimeout(function() {
    alert(i);
  }, 100);
}

for (var i = 1; i <= 2; ++i)
  doSetTimeout(i);

With this solution, you can successfully print the consecutive values 1 and 2 as intended.

The above is the detailed content of Why Does `setTimeout` in a `for`-Loop Print the Last Value Twice, and How Can I Fix It?. 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