1

有什么方法可以从另一个函数暂停以下一组延迟函数?我想通过执行另一个函数将所有内容暂停 10 秒。

我需要的是这样的:

function pause(){
pause sleepLoop() for 10 seconds
}

如果无法暂停以下执行,我可以杀死它吗?

function game() {
sleepLoop();
}

function sleepLoop() {
loop...
setTimeout('gameActions()',5000);
}

function gameActions() {
actions...
sleepLoop();
}
4

3 回答 3

1

将计时器存储在变量中。然后您可以使用clearTimeout停止它,并在 10 秒后重新启动它:

function game() {
   sleepLoop();
}

var sleepLoopTimeout;

function sleepLoop() {
    gameActions();
    sleepLoopTimeout = setTimeout(sleepLoop,5000);
}

function pause(){
    clearTimeout(sleepLoopTimeout);
    setTimeout(sleepLoop, 10000);
}

function gameActions() {
    // Actions
}
于 2012-04-09T23:10:21.893 回答
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
于 2012-04-09T19:37:36.223 回答
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();

除了上述之外,我不确定你在问什么。


要终止(清除)超时:

clearTimeout(gameTimeout);
clearTimeout(sleepTimeout);
于 2012-04-09T19:34:00.783 回答