Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop execution of function after fixed time in javascript

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);
like image 252
Bonnie Scott Avatar asked Mar 05 '13 15:03

Bonnie Scott


3 Answers

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.

like image 50
Alnitak Avatar answered Oct 20 '22 01:10

Alnitak


Count begins an endless loop, your code never reaches the setTimeout().

like image 1
Brad M Avatar answered Oct 20 '22 02:10

Brad M


Three issues:

  • Your timeout is set to fire in one millisecond
  • Your setTimeout will not be reached because count will never finish
  • Your alert 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.

like image 1
David Hedlund Avatar answered Oct 20 '22 01:10

David Hedlund