2011-11-18 63 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