2011-11-18 48 views
6

我有一些問題,與此代碼,當我點擊開始按鈕,一切工作正常,但是當我想clearInterval停止動畫它不工作,只是不斷循環...什麼我做錯了嗎?clearInterval不起作用?

var a = function() { 
    $("div").animate({height:300},"slow"); 
    $("div").animate({width:300},"slow"); 
    $("div").animate({height:100},"slow"); 
    $("div").animate({width:100},"slow"); 
} 

$(document).ready(function(){ 
    $("start").click(function(){ 

     setInterval(a,1000); 
    }); 

    $("stop").click(function(){ 
     clearInterval(a); 

    }); 

}); 

回答

13

你應該通過一個引用(你從setInterval獲得)來clearInterval方法將其清除。試試這個

var intervalId; 
var a = function() { 
    $("div").animate({height:300},"slow"); 
    $("div").animate({width:300},"slow"); 
    $("div").animate({height:100},"slow"); 
    $("div").animate({width:100},"slow"); 
} 

$(document).ready(function(){ 
    $("#start").click(function(){ 
     intervalId = setInterval(a,1000); 
    }); 

    $("#stop").click(function(){ 
     clearInterval(intervalId); 
    }); 

}); 
+0

只想說謝謝大家對這種迅速的回答!!!! –

+0

@Dejo - 很高興幫助你,請務必將其標記爲答案。 – ShankarSangoli

+0

$( 「開始」)應和$( 「#啓動」)...不是它... – Wazzzy

2

的 「的setInterval()」 函數返回的值。這就是你需要傳遞給「clearInterval()」,而不是對處理程序的引用。

1

這是否對你的工作:

 
var chk = setInterval(a,1000); 
then 
clearInterval(chk); 
2

HTML

<div style="height:310px;width:310px;"> 
    <div id="div" style="width:100px;height:100px;background-color:#000"> 
    </div> 
</div> 

<input type="button" id="start" value="start"> 
<input type="button" id="stop" value="stop"> 

JQUERY

VAR startInterval;

$(document).ready(function(){ 
    var a = function() { 
     $("#div").animate({height:300},"slow"); 
     $("#div").animate({width:300},"slow"); 
     $("#div").animate({height:100},"slow"); 
     $("#div").animate({width:100},"slow"); 
    } 
    $("#start").click(function(){ 
     startInterval=setInterval(a, 2500); 
    }); 

    $("#stop").click(function(){ 
     clearInterval(startInterval); 
    }); 
}); 

檢查了這一點參考jsfiddle

+0

的jsfiddle例如不工作 – Syno

+0

@Syno更新jsfiddle鏈接。還編輯了答案,請檢查。 – Wazzzy

+0

謝謝,現在工作:) @Wazzzy – Syno