开发者

setTimeout in Javascript

开发者 https://www.devze.com 2023-03-23 06:57 出处:网络
I\'m animating some process in javascript with this code: var direction = $(\'#rightControl\'); function animate()

I'm animating some process in javascript with this code:

  var direction = $('#rightControl');
  function animate()
  {
      if (hover) return;

      if (!direction.is(':visible'))
      {
          if (direction.attr('id') == 'rightControl') direction = $('#leftControl');
          else direction = $('#rightControl');
      }

      doMove(direction);
  }

  // Animate slider!
  setInterval(animate, 2500)开发者_如何转开发;

Until element #rightControl exists at page: call animate() function each 2.5 seconds and move my div (inside doMove). When the #rightControl dissappears I change direction into #leftControl, ...

Everything works cool, but when page is in background a few time (for example, 4-5 minutes), the animation becomes crazy and call each 100-200 ms. What's wrong?


Hmm, setInterval just adds something to the call-stack every * seconds. If there is some javascript being executed for a few seconds, things might build up on the call stack. That could happen if the page is in background too I guess. Check if it works with setTimeouts (so 1 or a function call to start it, 1 at the end of the function).


What I can guess is that either setInterval() is accidentally being called elsewhere, or animate() is.

Try this fiddle: http://jsfiddle.net/fXJbW/ It works fine with just animate() and setInterval(). The problem is in the rest of your code.

Another thing you can do is this:

var timeout;

function animate()
{
    // do stuff here
    clearTimeout(timeout);
    timeout=setTimeout(animate,2500);
}
0

精彩评论

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

关注公众号