I have some problem with this code, when I click the start button everything is working as expected but when I want to stop animation with clearInterval
it doesn’t work, just keeps looping... What I am doing wrong?
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);
});
});
You should pass a reference(which you get from setInterval
) to clearInterval
method to clear it. Try this
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);
});
});
The "setInterval()" function returns a value. That's what you need to pass to "clearInterval()", not a reference to the handler.
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);
});
});
Check this out for reference jsfiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With