首次点击jQuery setTimeout然后第二次点击clearTimeout

时间:2012-11-17 12:42:05

标签: jquery animation settimeout clear

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

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

到目前为止,我可以让超时工作正常,但我无法清除它并让动画停止。

HTML:

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

CSS:

div.block {
  position: absolute;
  display: block;
  height: 100px;
  width: 100px;
  top: -10px;
  left: 50%;
  background-color: red; }

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(); });
});

1 个答案:

答案 0 :(得分:2)

您需要定义函数范围的变量 outside ,以便稍后可以清除它。此外,您正在清除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(); });
});
相关问题