Joel
Joel

Reputation: 6107

Stopping animation that uses TimeOut with jQuery

I am using the jQuery's animate() function along with TimeOut() to create a ticker effect. Since the code is a bit long, and to better understand the effect, I uploaded the code to JSBin (click to see). The animation works great, but I want to make it pause when a user hovers with a mouse.

The most important part of the code (if you haven't gone to the JSBin link) that creates the ticker effect is:

var stocksTicker = function () {
    setTimeout(function () {
        $('#ticker li:first').animate({
            marginTop: '-27px'
        }, 800, function () {
            $(this).detach().appendTo('#ticker');
        });
        stocksTicker();
    }, 4000);
};
stocksTicker();​

I tried to make the pause effect by using the following code:

$('#ticker li').hover(function () {
    $('#ticker li:first').stop();
}, function () {
    stocksTicker();
});

but using this just messes up the whole animation (you can view the result here).

How can I get a normal pause effect that will not mess up my animation?

Thanks!

Joel

Upvotes: 1

Views: 639

Answers (2)

user372551
user372551

Reputation:

you can use clearTimeout

var tmr = null;
var stocksTicker = function () {
    tmr = setTimeout(function () {
        $('#ticker li:first').animate({
            marginTop: '-27px'
        }, 800, function () {
            $(this).detach().appendTo('#ticker').removeAttr('style');
        });
        stocksTicker();
    }, 1000);

};
stocksTicker();

$('#ticker li').hover(function () {
    clearTimeout(tmr)
}, function () {
    stocksTicker();
});

Try it here

Upvotes: 2

wajiw
wajiw

Reputation: 12269

I would put a check in there to gracefully stop(i.e. it finishes the animation if it's already started). Also I would use setInterval instead of setTimeout:

var run = true;
var stocksTicker = function()
{

      setInterval(function(){
        if(run){
            $('#ticker li:first').animate( {marginTop: '-27px'}, 800, function()
            {
                $(this).detach().appendTo('#ticker').removeAttr('style');
            });
        }
      }, 4000);

};
$('#ticker li').hover(
  function(){
     run = false; 
  },
  function(){
     run = true;
  });
stocksTicker();​

Upvotes: 0

Related Questions