stopping a function with animations in it with jquery/javascript
-
26-01-2021 - |
Question
Im building a custom timed image slider for a site, and im stuck on a basic principle. I have a recursive function that starts on the pageload. Im wondering how to immediatly stop the function and then restart it at the beginning with an onclick.
In the follwing jsfiddle example, can someone please tell me how i make the red square start at margin 0 and then start the bounce() function again, when the 'blue' or 'green' button is clicked?
for example: if the red square is towards the right, when 'blue' is clicked, how can i make the square appear at 'margin-left:0' and then have the bounce() function start again?
Thanks so much. http://jsfiddle.net/hZ6xZ/7/
Solution
Fiddle - http://jsfiddle.net/mrtsherman/hZ6xZ/9/
Use jQuery's stop() to kill the current animation. Also take a look into method chaining which is more efficient than calling $('#box') a lot of times.
$('#blue').click(function(){
repeat = clearTimeout(repeat);
$('.box')
.stop()
.css({'background-color':'blue'})
.css({'margin-left':'0'});
bounce();
});
OTHER TIPS
It's easy, jQuery got a function named stop() that stops animations, it also supports jump to end of animation and clear queue.
Just form your bounce function like this:
var repeat;
function bounce(){
$('.box')
.stop()
.css({'margin-left':'0px'})
.animate({'margin-left':'100px'})
.animate({'margin-left':'0px'});
repeat = setTimeout(function() { bounce(); }, 2000);
}
For more details about stop: http://api.jquery.com/stop/