CaribouCode
CaribouCode

Reputation: 14398

jQuery setTimeout on first click then clearTimeout on second

The first time a user clicks a button I want there to be a 3 second timeout set on a div before it is loop animated.

If the user then clicks a second time during that 3 seconds, I want the timeout to clear and the animation to stop.

So far I can get the timeout to work fine but I can't clear it and get the animation to stop.

The HTML:

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

The CSS:

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

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

Upvotes: 0

Views: 1293

Answers (1)

Christian
Christian

Reputation: 19740

You need to define the variable outside of the scope of the function so that you can clear it later on. Also, you're clearing rainTimer, yet you're defining it as 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(); });
});

Upvotes: 2

Related Questions