Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
659 views
in Technique[技术] by (71.8m points)

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

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...