Window.setTimeout behavior when the window is out of focus

Here is the simplest code to play that I could think of:

ms = 30; // 1000 ?
num = 1;
function test()
{
    num+=ms;
    document.getElementById('Submit').value = num; // Using native Javascript on purpose
    if (num < 4000)
        window.setTimeout(test, ms);
}
test()

I set ms (milliseconds between iterations) to 30, ran the script and moved to another tab in the browser.

Then I wait about 10 seconds (the script should end in 4 seconds) and will return to the tab.

If I used Firefox, I saw that the script is not finished yet, and the numbers are still working (resuming from where I left them, I think).

What annoys

But if I changed msto 1000 and repeated the above steps, when I return to the tab, I saw that the script has already been completed.

(It takes 4 seconds to complete the script).

, Firefox window.setTimeout, , . ,

, Internet Explorer.

script, . , ms.

  • Firefox?

  • ?

  • , ?

, ? ?

DOM , setInterval ( ).

  • , ?

, .

, , .

- , / , .

, .

, , , / .

Firefox 25.0.1 IE 11. (Windows 7)

+4
3

( ) , , (, requestAnimationFrame ). - / , .

, ( ), , - , , -. , , , , .

"(un) focus" , , "" . , , , .

+4

. : http://jsfiddle.net/qN6eB/

ms = 30; // 1000 ?
num = 1;
start = new Date();

function test()
{
    num+=ms;
    document.getElementById('Submit').value = num;
    if (num < 4000)
        window.setTimeout(test, ms);
    else
        document.getElementById('Time').value = new Date() - start;
}

test()



ms2 = 30; // 1000 ?
num2 = 1;
start2 = new Date();
dueTo = new Date(+new Date()+4000);

function test2()
{
    num2+=ms2;
    document.getElementById('Submit2').value = num2;
    if (new Date() < dueTo)
        window.setTimeout(test2, ms2);
    else 
        document.getElementById('Time2').value = new Date() - start2;
}
test2()
0

setTimeout . , . , , , , .

: - setInterval ( , ) - Date, , .

var beginTime = (new Date()).getTime();
var intervalId = setInterval(function() {
    var timePassed = (new Date()).getTime() - beginTime;
    document.getElementById('Submit').value = timePassed;
    if(timePassed >= 4000) {
        clearInterval(intervalId);
    }
}, 30);
-1

All Articles