I need to let a function run for a fixed number of seconds, then terminate. I could use jQuery or web workers, but my attempt at doing it directly faild.
Tks for help this now works:
startT = new Date().getTime();
i = 1;
while(true){
now = new Date().getTime();
if( (now - startT) > 100) {
break;
}
i++;
}
alert(i);
Your proposed method doesn't work because Javascript is (mostly) single threaded - the loop starts off in an infinite loop, so the setTimeout
handler never gets invoked, so keepGoing
never gets set, so the loop can't finish.
It would be simplest to determine an absolute time at which the function is to finish, and every so often (i.e. not on every iteration) check whether the current time has passed that point.
Pick a number of iterations that gives you a reasonable compromise between the efficiency of the test for elapsed time, and the amount of "overtime" you're prepared to let the function have.
Count begins an endless loop, your code never reaches the setTimeout().
Three issues:
setTimeout
will not be reached because count
will never finishalert
should be called from within count
after the while
, or from within the setTimeout
callback.Address those issues and your code should work. Still, I might have gone with setting an end date up front, and comparing with that date in the while
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With