清除运行时在它自己的函数中的超时

clearTimeout within it's own function while running

本文关键字:超时 函数 自己的 运行时 它自己 清除      更新时间:2023-09-26

我正在尝试调用一个函数,该函数在函数运行时清除超时(以停止动画循环)。这是我目前正在尝试的:

function gameStop(){
  clearTimeout(gameLoop);
}
function gameLoop() {
  $('h1').show("slow")
           .animate({"marginLeft":"300px"},4000)
            .animate({"marginLeft":"0px"},4000);
 $('h1').click(function(){
   gameStop();
 });
 gameLoop();
}
 setTimeout(gameLoop, 4000);
 gameLoop();

老实说,哇,这看起来很混乱。首先,您不希望在每个游戏循环中添加点击事件,因此请将其放在游戏循环之外的某个位置。第二:清除超时不是这样工作的。一般来说,同名的 nasting 函数非常糟糕......

尝试这样的事情(不知道代码是否有效,或者您的循环是否有意义,但这实际上是您想要的)。

var timeOut = null;  
$('h1').click(function(){
clearTimeout(timeOut);
});
function gameLoop(){
$('h1').show("slow")
    .animate({"marginLeft":"300px"},4000)
    .animate({"marginLeft":"0px"},4000);
};
timeOut = setTimeout(gameLoop, 4000);

我会将 timeout 存储在一个变量和一个标志中,以指示用户是否已停止游戏:

像这样的东西(未经测试)

var timeOut = null; 
var stopped = false; 
$('h1').click(function(){
stopped = true;
});
function gameLoop()
{
      clearTimeout(timeOut);
     $('h1').show("slow")
    .animate({"marginLeft":"300px"},4000)
    .animate({"marginLeft":"0px"},4000);
     if (!stopped)
     {
          timeOut = setTimeout(gameLoop, 100);
     }
};
timeOut = setTimeout(gameLoop, 4000);

你其实不需要setTimeout,用力,卢克!
使用 .animate() 回调循环函数:

现场演示

jQuery(function($) { // DOM ready
    function gameLoop() {
      $('h1').show("slow")
           .animate({marginLeft: 300}, 4000)
           .animate({marginLeft: 0  }, 4000, gameLoop); // LOOP HERE
    }
    gameLoop(); // START
    $('h1').click(function(){
       $(this).stop();
    });
});

甚至更简单:演示

var mrg = [300,0];
(function gameLoop() {
  $('h1').animate({marginLeft: mrg.reverse()[1]}, 4000, gameLoop);
})();
$('h1').click(function(){
   $(this).stop();
});

缓存选择器以获得稍微更好的性能
并根据当前保证金位置进行动画处理:演示

var $h1 = $('h1'); // Cache your selectors
(function gameLoop() {
  var m = parseInt( $h1.css('marginLeft'), 10);
  $h1.animate({marginLeft: m>0?0:300 }, 4000, gameLoop);
})();
$h1.click(function(){
   $(this).stop();
});