1

假设我打开了两个单独的浏览器窗口:

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

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

我想让它只在窗口处于焦点时每两秒打印一次 hello 。如果窗口不在焦点上,则计时器将基本上暂停(换句话说,计时器将停止滴答,不会调用dsomething),直到用户单击不在焦点的浏览器窗口,计时器将恢复并且Hello 单词将继续打印,而另一个窗口将停止计时器,反之亦然。

我该如何做到这一点?

4

2 回答 2

0

这是一个棘手的问题,并且取决于浏览器。

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;
}
于 2012-05-25T23:51:11.950 回答
0
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;
    }
}
于 2012-05-25T22:56:09.470 回答