Home >Web Front-end >JS Tutorial >Why Does a For-Loop with setTimeout Print Unexpected Values?

Why Does a For-Loop with setTimeout Print Unexpected Values?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-29 07:46:15930browse

Why Does a For-Loop with setTimeout Print Unexpected Values?

For-Loop Wrapped in setTimeout Prints Unexpected Values

In this script, a for-loop iterates with variable i from 1 to 2, and within the loop, a timeout function is set with a delay of 100 milliseconds to alert the value of i when it executes. However, the expected behavior is for the script to print 1 and 2 consecutively, but instead, 3 is alerted twice.

The unexpected behavior stems from the fact that i is shared throughout the loop and is modified as the loop progresses. By the time the timeout functions execute, i has already reached 3, leading to both alerts displaying that value.

To resolve this issue and ensure consecutive printed values, it's necessary to create separate copies of i for each timeout function. This can be achieved by defining a dedicated function, doSetTimeout, that takes i as an argument and sets the timeout using that specific value.

The modified script using doSetTimeout is as follows:

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

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

With this modification, each iteration of the loop creates a new copy of i that is passed to doSetTimeout, ensuring that each timeout executes with the correct value.

The above is the detailed content of Why Does a For-Loop with setTimeout Print Unexpected Values?. 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