Stop function after a certain time in javascript

I need the function to execute for a fixed number of seconds and then complete. I could use jQuery or web workers, but my attempt to do this directly failed.

Tks for reference now works:

startT = new Date().getTime(); i = 1; while(true){ now = new Date().getTime(); if( (now - startT) > 100) { break; } i++; } alert(i); 
+6
source share
4 answers

Your proposed method does not work, because Javascript is (mostly) single threaded - the loop starts in an infinite loop, so the setTimeout handler is never called, so keepGoing never set, so the loop can end.

It would be easier to determine the absolute time during which the function should end, and each so often (i.e. not at each iteration) checks whether the current time of this point has passed.

Choose a few iterations that give a reasonable compromise between past test performance and the amount of overtime that you are willing to provide features.

+3
source

Count starts an infinite loop, your code never reaches setTimeout ().

+1
source

Three questions:

  • Timeout configured to start within one millisecond
  • Your setTimeout will not be reached because count will never finish
  • Your alert should be called from count after while or from the setTimeout callback.

Fix these problems and your code should work. However, I may have gone with setting the end date forward and comparing with that date in while .

+1
source

I don’t know what the goal is, but you have to interrupt

 function count() { while(keepGoing) { i = i+1; } } 

for some time, to give a chance for keepGoing to change elsewhere, which runs in the meantime. Also you never do this:

 while(keepGoing) { i = i+1; } 

You completely block the flow for everything . You will need to divide the function into small pieces and use setTimeout or setInterval to run it in small batches, something like the following, while close to what you might need:

 var piece_n=0; var keepGoing = true; var interval_id = setInterval(function () { if(keepGoing){ //do_a_short_piece_of_work(piece_n); piece_n++; }else{ clearInterval(interval_id); } },500); //ticking every half second setTimeout(function () { keepGoing = false; }, 10000); //run for a small bit more than 10 to 10.5 seconds + do_a_short_piece_of_work() execution time 

If you need exactly 10 seconds without starvation, you will need to set up a setTimeout series, and you will need to know a little in advance (more than the next tick) so that you can set the last setTimeout at the exact time (consultation of the current date and the saved start date). Everything can be divided into smaller pieces, for example, instructions for the processor :)

0
source

All Articles