javascript changing global var setTimeout

55 Views Asked by At

I Want to make a loop to live 2 seconds, then brake after. This code wont work, the loop goes to end, it wont brake at 2 seconds. Why?

var stop = 0;
setTimeout(function() {
  stop = 1;
}, 2000);

for (var i = 0; i < 10000; i++) {
  console.log("wait" + stop);
  if (stop == 1) break;
}

Is there a workarround?

1

There are 1 best solutions below

7
Bergi On

A setTimeout callback will never interrupt a running synchronous loop. To achieve the desired result, you can change your loop head to

for (var i=0, timeout=Date.now()+2000; i<10000 && Date.now()<timeout; i++) …