Take the 2-minute tour ×

I would like to have a div that moves up and down repeatedly using jquery. In other words, the div starts at the top of some location, moves down and then moves back up and repeats this, in about a 1 second interval from going from top to bottom and 1 second back to the top. There's the slideUp and slideDown as well as animate methods but I'm not sure how to accomplish this since it needs to be in an endless loop and in javascript you must avoid such loops.

share|improve this question
can you prepare a jsfiddle demo of what you want –  Arun P Johny Aug 21 '13 at 4:54
How about setInterval? It's used to do the same action every X milliseconds. You use a variable like isDown, a boolean, which you alternate between true and false, each time animating your block up and down, and then a switch or a simple if to slide it up if it's down, and down if it's up. –  Ariane Aug 21 '13 at 4:59
callbacks should alleviate the need for a boolean flag –  chiliNUT Aug 21 '13 at 5:04
setInterval has its own timer and if I use slideUp/slideDown or animate, they use their own timers and I believe it is possible for the two to get out of sync. –  AndroidDev Aug 21 '13 at 5:17

2 Answers 2

up vote 6 down vote accepted

jQuery's animate logic can safely be called with callbacks or chained together without using setTimeout/setInterval:

Something like this should work just fine for you


function loop() {
    $('.bouncer').animate({'top': '500'}, {
        duration: 1000, 
        complete: function() {
            $('.bouncer').animate({top: 0}, {
                duration: 1000, 
                complete: loop});
share|improve this answer
That is so frikken cool! That seems to rule out using slideUp/slideDown. –  AndroidDev Aug 21 '13 at 5:19
Updated demo to show outer loop exiting just in case there were any doubts. –  dc5 Aug 21 '13 at 5:36
thanks! please mind that you are missing some single quotes on the complete function. –  Guido Celada Aug 29 at 1:20

use setInterval, see here: http://www.w3schools.com/js/js_timing.asp

so try this


$(document).ready(function() {
    setInterval(function() {
        $('#thediv').slideUp('500', function() {
    }, 1000);


<div id='thediv' style='width:100px;height:200px;border:1px solid black;'>
Div Contents

you may need to tweak the timings (which are in miliseconds)

share|improve this answer
I thought about that, but you are using a setInterval that contains a timer interval in addition to a separate animation time of 500 ms. That's not good because the two could essentially get out of sync. –  AndroidDev Aug 21 '13 at 5:14
without an (agreeably) bad infinite loop I don't see doing this without setinterval –  chiliNUT Aug 21 '13 at 5:16
@dc5 shows that it can be done! –  AndroidDev Aug 21 '13 at 5:20
Oh calling loop on callback that makes sense. Neat. –  chiliNUT Aug 21 '13 at 5:46

Your Answer


