简体   繁体   中英

Javascript execute timer function only if window is in focus?

Say I have two separate browser windows open:

function onload() {
    setTimeout("dosomething", 2000);
}

function dosomething() {
    $.ajax({
        url: "someurl",
        success: function (data) {
            document.write("Hello");
        }
    });
    setTimeout("dosomething", 2000);
}

I want to make it so that hello is printed every two seconds only when the window is in focus. If the window is not in focus, then the timer would essentially pause (in other words, timer would stop ticking, dosomething would not be called) until the user clicks on the browser window that is not in focus, which the timer would resume and the Hello words would continue to be printed, while the other window would stop timer, vice versa.

How do I accomplish this?

var someVar = false;
window.onfocus = function() { someVar = true; };
window.onblur = function() { someVar = false; };
var time;

function timer(someVar) {
    if (someVar == true) {
        setTimeOut('time++', 1);
    }
}

function something() {
    time = 0;
    while (time <= 2000) {
        timer(someVar);
        document.getElementById('time').innerHTML = time;
    }
}

This is tricky one, and depend on browser.

var timer;    
function onBlur() {
    timer = setTimeout("dosomething", 2000);
};
function onFocus(){
    clearTimeout(timer);
};
if (/*@cc_on!@*/false) { // check for Internet Explorer
    document.onfocusin = onFocus;
    document.onfocusout = onBlur;
} else {
    window.onfocus = onFocus;
    window.onblur = onBlur;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM