Search code examples
javascriptsettimeout

Trying to run a loop for exactly one second, but the loop runs infinitely. why?


i am changing the value of 'aa' after 1 second, but the loop continues to execute.

let aa = true;

setTimeout(function () {
  aa = false;
}, 1000);

for (; aa; ) {
  console.log('aaa');
}

Solution

  • Your approach doesn’t work for reasons explained by others. You can use something like this instead:

    var started = Date.now();
    while(Date.now() - started < 1000) {
      console.log("aaa");
    };