2012-11-17 211 views
0

第一次用户点击一个按钮我希望在循环动画之前在div上设置3秒的超时时间。第一次点击jQuery setTimeout然后第二次点击clearTimeout

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

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

的HTML:

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

请让一个js小提琴的问题 – rahul

回答

2

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

啊当然是!现在看起来很明显。对不起,我错误地键入了rainTimer,我在原始代码中正确输入了它。这个答案是正确的。 – Coop