开发者

Stopping animation that uses TimeOut with jQuery

开发者 https://www.devze.com 2023-01-29 21:07 出处:网络
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 se

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 importa开发者_开发百科nt 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


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


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();​
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号