How to stop execution of the function or loop after a time?

There is a function game() in which the code executes. So after the time it should close itself/to stop executing. Is this possible? Thank you
June 27th 19 at 15:06
1 answer
June 27th 19 at 15:08
Solution
You can, for example, a flag to raise when the time function stop working. And inside the function to see whether the flag is raised, and if so – to go.
var flag = false; // when true - put out the light!
function game() {
 var i;
 while(true) { // really out of the loop so not to go
 // while it is spinning, no other threads will not be able to start and change the value of the flag
 i = i++;
 if(flag) return; // exit when it's time
}
}
setTimeout( function(){ flag = true;}, 60000}); // in a minute to raise the flag
game();


Another option that is more suitable for cycle - pre-assign exit time and watch the clock:
var timeToExit = (new Date).getTime() + 300000; // 5 minutes
function game() {
 var i;
 while(true) {
 i = i++;
 if( (new Date).getTime() >= timeToExit) return; // exit when it's time
}
}
game();
I thought about it. Just hoped that there is a decision better, but hike no. - nikita.Stracke commented on June 27th 19 at 15:11
: generally directly my example doesn't work. JS runs in single thread, so the cycle will spin, preventing breathing function by timeout. Another thing, if the inside game() is an asynchronous call then the timeout will have a chance to break through. - Lorena commented on June 27th 19 at 15:14

Find more questions by tags JavaScript