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

Time:12-12

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');
}

CodePudding user response:

setTimeout is asynchronous, so it will execute only after the current code execution of for loop completed. In your case it will go infinite.

Once for loop started execution, it will stay in the call stack until finished. Since you didn't give any condition there it won't stop

CodePudding user response:

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");
};

  • Related