简体   繁体   中英

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

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 (ie 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开始无限循环,您的代码永远不会到达setTimeout()。

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 .

I don't know what is the purpose but you would have to interrupt

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

for a while to give a chance for keepGoing to change in some other place that runs meanwhile. Also you never do this:

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

You are completely blocking the thread for everything ... You will have to divide your function's work into small pieces and use setTimeout or setInterval to run it in small batches, something like the following, while close to what you may want:

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 starving the rest you will need to adjust in a series of setTimeout and you will need to know a bit in advance (more than next tick) so you can set the last setTimeout at the exact time (consulting current date and saved initial date). Everything can be divided into smaller chunks, like instructions for a cpu :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM