1

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();
}
1
  • 1
    Blocking running JS is not a good idea. Perhaps if you elaborate why you want to we can give you a better solution? Commented Apr 9, 2012 at 19:37

3 Answers 3

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0
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

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.
@Neal I don't think this it the most elegant solution but I don't think it'll run slow. Care to elaborate?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.