clearInterval不起作用?
问题描述:
我有一些问题,与此代码,当我点击开始按钮,一切工作正常,但是当我想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);
});
});
答
你应该通过一个引用(你从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);
});
});
答
的 “的setInterval()” 函数返回的值。这就是你需要传递给“clearInterval()”,而不是对处理程序的引用。
答
这是否对你的工作:
var chk = setInterval(a,1000); then clearInterval(chk);
答
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
只想说谢谢大家对这种迅速的回答!!!! –
@Dejo - 很高兴帮助你,请务必将其标记为答案。 – ShankarSangoli
$( “开始”)应和$( “#启动”)...不是它... – Wazzzy