什么加速“setInterval”当你切换页面? [英] what speed up "setInterval" when you switch page?
问题描述
这是我的页面,这是一个测试移动元素的演示,但是在你改变你的页面之后,回到这里,为什么DIV移动得更快?
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?
我的css:
#box1 {
width: 900px;
height: 50px;
background-color: #000;
position: relative;
}
#box2 {
width: 50px;
height: 50px;
background-color: #a00;
position: absolute;
}
我的HTML:
<div id="box1">
<div id="box2"></div>
</div>
我的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)
推荐答案
Mozilla Firefox和谷歌浏览器都会限制标签处于非活动状态时的间隔速度(来源: http://pivotallabs.com/users/mrushakoff/blog/articles/2035-chrome-and-firefox-throttle- settimeout-setinterval-in-inactive-tabs , https://stackoverflow.com/a/6032591/1756941)
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:
var tick = 20;
var newLeft=0;
var box2 = document.getElementById("box2");
var remove = setInterval(function() {
box2.style.left = "0px";
var now, before = new Date();
var move = setInterval(function() {
now = new Date();
var elapsedTime = (now.getTime() - before.getTime());
if (elapsedTime > tick) {
console.log((Math.floor(elapsedTime / tick) * 5));
newLeft = Math.min(parseInt(box2.style.left) + (Math.floor(elapsedTime / tick) * 5), 850) + "px";
}
else {
newLeft = Math.min(parseInt(box2.style.left) + 5, 850) + "px";
}
box2.style.left = newLeft;
before = new Date();
if (newLeft == "850px"){clearInterval(move);}
}, tick);
}, 5000);
JSFiddle: http://jsfiddle.net/3jY8h/1/
JSFiddle: http://jsfiddle.net/3jY8h/1/
这篇关于什么加速“setInterval”当你切换页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!