Is there any way I can pause the below set of delayed functions from another function? I want to pause everything for 10 seconds by executing another function.
What I need is something like:
function pause(){
pause sleepLoop() for 10 seconds
}
If it is not possible to pause the below execution, can I kill it?
function game() {
sleepLoop();
}
function sleepLoop() {
loop...
setTimeout('gameActions()',5000);
}
function gameActions() {
actions...
sleepLoop();
}
-
1Blocking running JS is not a good idea. Perhaps if you elaborate why you want to we can give you a better solution?Snuffleupagus– Snuffleupagus2012年04月09日 19:37:12 +00:00Commented Apr 9, 2012 at 19:37
3 Answers 3
Store the timer in a variable. Then you can stop it with clearTimeout, and restart it after 10 seconds:
function game() {
sleepLoop();
}
var sleepLoopTimeout;
function sleepLoop() {
gameActions();
sleepLoopTimeout = setTimeout(sleepLoop,5000);
}
function pause(){
clearTimeout(sleepLoopTimeout);
setTimeout(sleepLoop, 10000);
}
function gameActions() {
// Actions
}
answered Apr 9, 2012 at 23:10
Paul
142k28 gold badges285 silver badges272 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
var gameTimeout, sleepTimeout;
function game() {
gameTimeout = setTimeout(sleepLoop, 10000); //start in 10 seconds
}
function sleepLoop() {
sleepTimeout = setTimeout(gameActions, 5000); //start in 5 secs
}
function gameActions() {
sleepLoop();
}
//start it off:
game();
Other than the above, I am not sure what you are asking.
To kill (clear) the timeouts:
clearTimeout(gameTimeout);
clearTimeout(sleepTimeout);
answered Apr 9, 2012 at 19:34
Naftali
147k41 gold badges247 silver badges304 bronze badges
Comments
var blocked = false;
function loopToBePaused()
{
if (blocked !== false)
{
// will check for blocker every 0.1s
setTimeout(loopToBePaused, 100);
return;
}
// payload
// normal loop now, e.g. every 1s:
setTimeout(loopToBePaused, 1000);
}
// somewhere in code run:
blocked = setTimeout(function() {
// blocking our loop'ed function for 10s
blocked = false;
}, 10000);
// this will block our main loop for 10s
2 Comments
Botanick
Rly? Never noticed. You cannot implement game ticks in other way however. Also, timeouts are to be adjusted for every specified task: somewhere longer, somewhere shorter.
Snuffleupagus
@Neal I don't think this it the most elegant solution but I don't think it'll run slow. Care to elaborate?
lang-js