简体   繁体   中英

Why is my JavaScript loop with time delay (using setTimeout) not modifying variables?

I wanted to write a loop in JavaScript which has a delay after each iteration. I tried incrementing elements in an array. But it's not modifying the elements in the array at all!

let A = [1, 2, 3, 4];
let N = A.length;

let f = i => {
  setTimeout(
    () => {
      A[i] += 1;
      if (++i < N) {
        f(i);
      }
    },
    100
  );
}

f(0);
console.log(A);

The expected output is [2, 3, 4, 5] , but I'm getting [1, 2, 3, 4] . If I add console.log(A[i]) after the increment

let A = [1, 2, 3, 4];
let N = A.length;

let f = i => {
  setTimeout(
    () => {
      A[i] += 1;
      console.log(A[i]);
      if (++i < N) {
        f(i);
      }
    },
    100
  );
}

f(0);
console.log(A);

it prints out the expected values 2 3 4 5 . But console.log(A) still prints the original array [1, 2, 3, 4] . OTOH, it works if I use a for loop.

let A = [1, 2, 3, 4];
let N = A.length;

for (let i = 0; i < N; i++) {
  A[i] += 1;
}

console.log(A);

Am I missing something obvious?

Why is my JavaScript loop with time delay (using setTimeout) not modifying variables?

It is modifying the variables. But you're observing the variables before they're modified. The order of operations for your code is effectively:

  1. Define an array.
  2. Schedule the array to be modified later.
  3. Log the array to the console.
  4. Modify the array.

(As a note on debugging, your biggest clue to this behavior should be that the entire "incorrect" array is logged before each of the "correct" values is logged.)

So the code is working as expected, you just need to observe the result after the code has performed its task.

Currently the array has 4 elements, so the modification should take a total of 400ms. Set it to log to the console after 500ms and observe the updated array:

setTimeout(() => console.log(A), 500);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM