我正在创建一个聊天室,该聊天室需要定期使用AJAX从PHP检索消息。问题在于用户可以打开不同聊天室的多个选项卡,这将占用服务器大量资源。因此,当用户切换页面时,如何在其他选项卡中停止功能,然后在他们返回到选项卡时对其进行响应。我是编码的新手,因此请尽可能简化代码(请不要使用jQuery。)
这是我正在尝试的功能测试,但是没有运气:
function window_active(){
window.onfocus = function() {
test()
};
window.onblur = function() {
//stop the script OR change the setTimeout so the functon run less.
};
}
function test(){
alert('adadasdad');
setTimeout(function(){}, 10000);
}
Run Code Online (Sandbox Code Playgroud)
提前致谢。(:
更新:requestAnimationFrame()无法正常工作。
function loop() {
var div_id = document.getElementById('tester');
var msg = document.createTextNode("sadksadkjsahdjkasdjkahdjkas");
div_id.appendChild(msg);
setTimeout( function() {
requestAnimationFrame( function() {
loop();
} );
}, 1000 );
}
Run Code Online (Sandbox Code Playgroud)
更新 2:Counldn在任何地方都找不到此答案,然后我很幸运,并在有关“ document.hidden”的ehynds答案的帮助下找到了此页面。谢谢,谢谢!(:
function loop() {
//do stuff.
setTimeout( function() {
if(document.hasFocus()){
//"document.hasFocus()" return **true** only if your on the tab.
loop();
}
}, 1000);
window.onfocus = function() {
//reactivted the function.
loop();
};
}
Run Code Online (Sandbox Code Playgroud)
希望这对寻求答案的人有所帮助。(:
HTML5可见性API:
document.addEventListener('visibilitychange', function() {
document.hidden; // whether or not the tab is visible
});
Run Code Online (Sandbox Code Playgroud)