最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - what speed up "setInterval" when you switch page? - Stack Overflow

programmeradmin3浏览0评论

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)

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)
Share Improve this question asked Dec 20, 2012 at 3:12 xiaomoxiaomo 311 silver badge5 bronze badges 3
  • Fit as a jsFiddle – Matchu Commented Dec 20, 2012 at 3:14
  • What do you mean by "switch page"? Navigating back and forth? – Bergi Commented Dec 20, 2012 at 3:16
  • 2 Open the fiddle. Click to another tab/window and then click back to the fiddle. Sometimes it has to catch up. – qooplmao Commented Dec 20, 2012 at 3:17
Add a ment  | 

3 Answers 3

Reset to default 6

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()).

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.

Mozilla Firefox and Google Chrome both throttle the speed of ticks that an interval when the tab is inactive (Sources: http://pivotallabs./users/mrushakoff/blog/articles/2035-chrome-and-firefox-throttle-settimeout-setinterval-in-inactive-tabs, https://stackoverflow./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 pensate 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/3jY8h/1/

发布评论

评论列表(0)

  1. 暂无评论