如何判断浏览器/选项卡是否处于活动状态 [英] How to tell if browser/tab is active
问题描述
我有一个每秒调用的函数,如果当前页面在前台,即用户,我只想运行没有最小化浏览器或切换到另一个选项卡。如果用户没有看到它并且可能是CPU密集型的话,它没有用处,所以我不想在后台浪费周期。
I have a function that is called every second that I only want to run if the current page is in the foreground, i.e. the user hasn't minimized the browser or switched to another tab. It serves no purpose if the user isn't looking at it and is potentially CPU-intensive, so I don't want to just waste cycles in the background.
有人知道如何在JavaScript中告诉它吗?
Does anyone know how to tell this in JavaScript?
注意:我使用jQuery,所以如果你的答案使用它,那很好:)。
Note: I use jQuery, so if your answer uses that, that's fine :).
推荐答案
您可以使用焦点
和模糊
窗口事件:
You would use the focus
and blur
events of the window:
var interval_id;
$(window).focus(function() {
if (!interval_id)
interval_id = setInterval(hard_work, 1000);
});
$(window).blur(function() {
clearInterval(interval_id);
interval_id = 0;
});
回答双火的评论问题并保持在jQuery易用性中:
To Answer the Commented Issue of "Double Fire" and stay within jQuery ease of use:
$(window).on("blur focus", function(e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
switch (e.type) {
case "blur":
// do work
break;
case "focus":
// do work
break;
}
}
$(this).data("prevType", e.type);
})
这篇关于如何判断浏览器/选项卡是否处于活动状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!