如何停止并启动功能?

时间:2014-12-06 01:18:36

标签: javascript jquery

我只是想在这里指出正确的方向。我是javascript的初学者,所以有些基本的东西我不理解。谷歌的搜索似乎并没有帮助,因为显然这个问题从来没有真正被问过。

按下Go按钮后,我有一个60秒倒计时的游戏。现在,当60秒倒计时正在运行时,我想运行一个函数orientationStuff(),它可以在orientationchange上完成所有类型的操作。这没问题......但是

我只希望orientationStuff()在60秒倒计时期间运行。所以一旦它达到0,就不再有orientationStuff()了。但是一旦你再次点击Go我想要倒计时再次开始(因此orientationStuff()

3 个答案:

答案 0 :(得分:2)

在Javascript中尝试这样的事情:

var i = 0; //counts every frame at 60FPS
function countdown() {
    function frame() {
        i += 1; //up the frame by 1;
        /* do stuff; you can use variable switch-based logic to perform different functions*/
        if(i > 3599) { /* equivilant of 60 seconds, you can add your own condition in if you want*/
            i = 0;
            clearInterval(looper_interval); //stops
        }
    }
    var looper_interval = setInterval(frame, 16); //this code runs the function frame() every 16 milliseconds
}

答案 1 :(得分:2)

简单的答案是你使用setTimeout和你想要执行的函数以及60000毫秒

setTimeout(function(){
   // do whatever you want to happen here
},60000)

在使用jQuery启动时,如果你有一个类go的按钮,你会使用

$(document).on('click','.go',function(){
    setTimeout(function(){
       // Game over man! GAME OVER!!
    },60000)
});

我猜你可能想要停止计时器 - 比如玩家是否赢了比赛。在这种情况下,你捕获了一个" id"从计时器,你可以使用clearTimeout来阻止它

var gameTimerId = null;
$(document).on('click','.go',function(){
    gameTimerId  = setTimeout(function(){
       // Hury, before someone calls clearTimeout
    },60000)
});

/// where the player wins
clearTimeout(gameTimerId);

setTimeout运行一次该函数。如果你想重复执行一个函数,你也可以使用类似的函数setInterval

答案 2 :(得分:0)

尝试使用setTimeout 60秒并切换您在提供orientationStuff()时看到的布尔值。

如果setTimeout在函数内部,您可以简单地重置布尔值并重新运行按钮上的函数。

<强>更新

var orientationAllowed = false;
function orient() {
  orientationAllowed = true;
  setTimeout(function(){
    orientationAllowed = false;
  },60000);
}
相关问题