可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Here is My page,It is a demo to test moving a element,but after you change your page sometime,and back to here,why the DIV move faster?
My css:
#box1 { width: 900px; height: 50px; background-color: #000; position: relative; } #box2 { width: 50px; height: 50px; background-color: #a00; position: absolute; }
My HTML:
<div id="box1"> <div id="box2"></div> </div>
My Js:
var box2 = document.getElementById("box2"); var remove = setInterval(function () { box2.style.left = "0px"; var move = setInterval(function () { var newLeft = Math.min(parseInt(box2.style.left) + 5, 850) + "px"; box2.style.left = newLeft; if (newLeft == "850px") clearInterval(move) }, 20); }, 5000)
回答1:
Mozilla Firefox and Google Chrome both throttle the speed of ticks that an interval when the tab is inactive (Sources: http://pivotallabs.com/users/mrushakoff/blog/articles/2035-chrome-and-firefox-throttle-settimeout-setinterval-in-inactive-tabs, https://stackoverflow.com/a/6032591/1756941)
And so, as this answer suggests, capture the date and check it against the tick, to verify if it's working correctly, else compensate for the missing time..
JS:
JSFiddle: http://jsfiddle.net/3jY8h/1/
回答2:
The rate of setInterval
cannot be trusted. A browser might not fire it when the tab is not focused, and as well might fire it more often than needed.
The behaviour is standardisized in the current HTML5 draft on the WindowTimers
interface (which does not mean it was implemented like that). There you will find the note:
This API does not guarantee that timers will run exactly on schedule. Delays due to CPU load, other tasks, etc, are to be expected.
and, even more explicit:
9) Optionally, wait a further user-agent defined length of time.
Note: This is intended to allow user agents to pad timeouts as needed to optimise the power usage of the device. For example, some processors have a low-power mode where the granularity of timers is reduced; on such platforms, user agents can slow timers down to fit this schedule instead of requiring the processor to use the more accurate mode with its associated higher power usage.
You might also want to have a look at the WindowAnimationTiming
draft.
And if you do use setInterval
/setTimeout
in animations/clocks/etc, always measure the really elapsed time with Date
objects (e.g. via Date.now()
).
回答3:
Some browsers don't bother to fire timeout/interval events if the window is unfocused. When the window regains focus, it fires all of them at once. It's a performance decision (Why fire an event every millisecond if the user won't even notice?), and, to my knowledge, there's no way to change this behavior.