是否有可能在JavaScript中检测“空闲”时间?
我的主要用例可能是预取或预加载内容。
我将空闲时间定义为用户不活动或没有任何CPU使用的时间段
是否有可能在JavaScript中检测“空闲”时间?
我的主要用例可能是预取或预加载内容。
我将空闲时间定义为用户不活动或没有任何CPU使用的时间段
当前回答
我也遇到过同样的问题,但我找到了一个很好的解决方案。
我使用jquery。无所事事,我只需要做:
$(document).idle({
onIdle: function(){
alert('You did nothing for 5 seconds');
},
idle: 5000
})
参见JsFiddle演示。
(仅供参考:查看后端事件跟踪Leads browserload)
其他回答
你可以用Underscore.js和jQuery更优雅地做到这一点:
$('body').on("click mousemove keyup", _.debounce(function(){
// do preload here
}, 1200000)) // 20 minutes debounce
你也许可以使用上面列出的鼠标移动技巧来检测网页上的不活跃状态,但这并不能告诉你用户不在另一个窗口或选项卡的另一个页面上,或者用户在Word、Photoshop或WoW中,只是在这个时候没有在看你的页面。
一般来说,我只会预取,并依赖于客户端的多任务处理。如果你真的需要这个功能,你可以在Windows中使用ActiveX控件做一些事情,但它充其量是丑陋的。
下面是一个在Angular中完成的AngularJS服务。
/* Tracks now long a user has been idle. secondsIdle can be polled
at any time to know how long user has been idle. */
fuelServices.factory('idleChecker',['$interval', function($interval){
var self = {
secondsIdle: 0,
init: function(){
$(document).mousemove(function (e) {
self.secondsIdle = 0;
});
$(document).keypress(function (e) {
self.secondsIdle = 0;
});
$interval(function(){
self.secondsIdle += 1;
}, 1000)
}
}
return self;
}]);
请记住,这个空闲检查器将为所有路由运行,因此应该在angular应用程序加载时在.run()中初始化它。然后你可以使用idleChecker。在每个路由内的secondside。
myApp.run(['idleChecker',function(idleChecker){
idleChecker.init();
}]);
下面是tvanfosson的想法的粗略jQuery实现:
$(document).ready(function(){
idleTime = 0;
//Increment the idle time counter every second.
var idleInterval = setInterval(timerIncrement, 1000);
function timerIncrement()
{
idleTime++;
if (idleTime > 2)
{
doPreload();
}
}
//Zero the idle timer on mouse movement.
$(this).mousemove(function(e){
idleTime = 0;
});
function doPreload()
{
//Preload images, etc.
}
})
我的回答受到了维贾伊的启发,但我认为这是一个更简短、更普遍的解决方案,我想把它分享给可能有帮助的人。
(function () {
var minutes = true; // change to false if you'd rather use seconds
var interval = minutes ? 60000 : 1000;
var IDLE_TIMEOUT = 3; // 3 minutes in this example
var idleCounter = 0;
document.onmousemove = document.onkeypress = function () {
idleCounter = 0;
};
window.setInterval(function () {
if (++idleCounter >= IDLE_TIMEOUT) {
window.location.reload(); // or whatever you want to do
}
}, interval);
}());
按照目前的情况,这段代码将立即执行,并在3分钟内没有鼠标移动或按键后重新加载当前页面。
它利用普通的JavaScript和立即调用的函数表达式以一种干净且自包含的方式处理空闲超时。