2012-11-17 208 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