Infinite looped vertical slider with no pause

1k Views Asked by At

I wrote a script

setInterval(function(){ 
  $('#vslides').animate({
    top: "-=1960"
  }, 60000, function(){                                 
    $('.vslide:last').after($('.vslide:first'));
    $('#vslides').css('top', '0px');
  }); 
}, 60000);

It works nice, scrolls the almost 2000px image in a minute, but, at the end it stops. I need it to continue to the next image (same image, just repeated) and keep going... I have tried several things, but can't seem to get it right. How do I make it continuous, and remove the stop/pause at the end of the interval?

1

There are 1 best solutions below

10
On BEST ANSWER

You need some kind of recursive function. Here's a solution that provides a single function for animating one element, but also accepts a callback function. Then we create a second function that will recursively iterate through all the elements in a wrapped set, call our animating function, and pass in a callback that will increment our index and call our recurse function again to animate the next element.

// slides an element
function slideIt($elem, callback) {
  /* begin animation */
  $elem.animate({
    top: "-=1960"
  }, 60000, function () {

    /* animation complete do whatever you need here */

    if (callback) {
      /* a callback was provided, invoke it */
      callback();
    }
  });
}

var $elems = $('.all-my-elements');
var index = 0;

// slides a wrapped set of elements one at a time
function slideRecurse () {
  var $elem = $elems.eq(index);
  slideIt($elems.eq(index), function () {
    /* increment index and call slideRecurse again */
    index++;
    // continue animating indefinitely
    // we're at the end so start over
    if (index === $elems.length) {
      index = 0;
    }
    setTimeout(slideRecurse, 0); // no delay. Just using it to queue up the next call on its own stack.
  });
}

// begin sliding all of my $elems one by one
slideRecurse();