Reputation: 1508
I have an animation every one second and I have a button Stop, when I click to the button the animation is stopped but it continues after. There is not another way to remove the animation ? This is my code.
$(document).ready(function() {
setInterval(function() {
$("#myImg").animate({top: '50%',left: '50%',width: '174px',height: '174px',padding: '10px'}, 500);
$("#myImg").animate({ marginTop: '0',marginLeft: '0',top: '0',left: '0',width: '70px',height: '70px',padding: '5px'}, 600);
},1000);
});
$("#stop").click(function(){
$("#myImg").stop();
});
Thank you
Upvotes: 3
Views: 630
Reputation: 206669
.animate()
callback to loop your anim
function..stop()
method on your first .animate()
iteration just to prevent animation buildups and clear some animation memory ;)$(document).ready(function() {
function anim(){
$("#myImg").stop().animate({top: '50%',left: '50%',width: '174px',height: '174px',padding: '10px'}, 500, function(){
$(this).animate({ marginTop: '0',marginLeft: '0',top: '0',left: '0',width: '70px',height: '70px',padding: '5px'}, 600, anim); // <-- the 'anim' callback
}); // SCROLL THERE --> TO FIND THE CALLBACK :D -->
}
anim(); // run!!
$("#stop").click(function(){
$("#myImg").stop();
});
});
Upvotes: 3
Reputation: 14737
The setInterval()
call is continuously adding in new calls to .animate()
to your elements. That means that you succeed in stopping the animation, then the setInterval()
calls it again, making the animation run again.
Why do you have this on setInterval()
?
In any case, you'll have to cancel the schedule as well. You can do that by doing something similar to the following:
var schedule = setInterval(fn, 1000);
clearInterval(schedule);
Upvotes: 1