清除运行时在它自己的函数中的超时
clearTimeout within it's own function while running
我正在尝试调用一个函数,该函数在函数运行时清除超时(以停止动画循环)。这是我目前正在尝试的:
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();
});
相关文章:
- 将变量传递到超时函数的Javascript
- 如何循环设置超时函数
- Jquery-超时函数
- 传递到超时函数时删除的小数点
- 如何通过密钥输入重新触发超时函数
- Javascript 在 for 循环中设置了超时函数
- 中断 JQuery 设置超时函数
- 设置超时函数回调静态变量
- 在浏览器空闲后保持设置超时函数运行
- 如何设置超时函数
- 强制 JavaScript 超时函数立即执行
- jQuery 超时函数从未在 mouseEnter mouseleave 上调用过
- 具有可变时间的设置超时函数
- jQuery动画到底后超时函数
- 超时函数完成后如何调用函数
- 如何创建一个rucursive超时函数
- javascript超时函数
- 多个设置超时函数在第一次单击时不执行
- 访问超时函数内的变量
- 在对象中设置超时函数