Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
第一次单击jQuery setTimeout,第二次单击clearTimeout_Jquery_Animation_Settimeout - Fatal编程技术网

第一次单击jQuery setTimeout,第二次单击clearTimeout

第一次单击jQuery setTimeout,第二次单击clearTimeout,jquery,animation,settimeout,Jquery,Animation,Settimeout,用户第一次单击按钮时,我希望在循环设置动画之前在div上设置3秒超时 如果用户在这3秒钟内再次单击,我希望清除超时并停止动画 到目前为止,我可以让超时正常工作,但我不能清除它,让动画停止 HTML: <a href="#" class="button">Button</a> <div class="block"></div> jQuery: $('a.button').toggle(function(){ var blockTimer;

用户第一次单击按钮时,我希望在循环设置动画之前在div上设置3秒超时

如果用户在这3秒钟内再次单击,我希望清除超时并停止动画

到目前为止,我可以让超时正常工作,但我不能清除它,让动画停止

HTML:

<a href="#" class="button">Button</a>
<div class="block"></div>
jQuery:

$('a.button').toggle(function(){
    var blockTimer;
    blockTimer = setTimeout(function block(){
      $("div.block").animate({top: '400px'}, 4000, 'linear', function() { $(this).css('top', '-10px'); block(); });
        },3000);
}, function(){
clearTimeout(rainTimer);
    $('div.block').clearQueue().stop().fadeOut(500, function() { $(this).css('top', '-10px').show(); });
});

您需要在函数范围之外定义变量,以便稍后清除它。此外,您正在清除
rainTimer
,但您将其定义为
blockTimer

var blockTimer;

$('a.button').toggle(function(){
    blockTimer = setTimeout(function block() {
        $("div.block").animate({top: '400px'}, 4000, 'linear', function() { $(this).css('top', '-10px'); block(); });
        }, 3000);
}, function() {
    clearTimeout(blockTimer);
    $('div.block').clearQueue().stop().fadeOut(500, function() { $(this).css('top', '-10px').show(); });
});

请把问题弄得一团糟啊,是的,当然!现在看来很明显。很抱歉,我打错了rainTimer,我的原始代码中的rainTimer是正确的。不过,这个答案是正确的。
var blockTimer;

$('a.button').toggle(function(){
    blockTimer = setTimeout(function block() {
        $("div.block").animate({top: '400px'}, 4000, 'linear', function() { $(this).css('top', '-10px'); block(); });
        }, 3000);
}, function() {
    clearTimeout(blockTimer);
    $('div.block').clearQueue().stop().fadeOut(500, function() { $(this).css('top', '-10px').show(); });
});