是否有可能在JavaScript中检测“空闲”时间?
我的主要用例可能是预取或预加载内容。
我将空闲时间定义为用户不活动或没有任何CPU使用的时间段
是否有可能在JavaScript中检测“空闲”时间?
我的主要用例可能是预取或预加载内容。
我将空闲时间定义为用户不活动或没有任何CPU使用的时间段
当前回答
我写了一个简单的jQuery插件,将做什么你正在寻找。
https://github.com/afklondon/jquery.inactivity
$(document).inactivity( {
interval: 1000, // the timeout until the inactivity event fire [default: 3000]
mouse: true, // listen for mouse inactivity [default: true]
keyboard: false, // listen for keyboard inactivity [default: true]
touch: false, // listen for touch inactivity [default: true]
customEvents: "customEventName", // listen for custom events [default: ""]
triggerAll: true, // if set to false only the first "activity" event will be fired [default: false]
});
脚本将监听鼠标,键盘,触摸和其他自定义事件不活动(空闲),并触发全局“活动”和“不活动”事件。
其他回答
下面是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.
}
})
JavaScript没有办法告诉CPU的使用情况。这将打破运行在沙盒中的JavaScript。
除此之外,连接页面的onmouseover和onkeydown事件可能会工作。
你也可以在onload事件中使用setTimeout来调度延迟后调用的函数。
// Call aFunction after 1 second
window.setTimeout(aFunction, 1000);
您可能可以通过检测窗体主体上的鼠标移动并使用最后的移动时间更新全局变量来拼凑一些东西。然后,您需要运行一个间隔计时器,定期检查最后一次移动时间,如果距离检测到最后一次鼠标移动已经足够长,则执行一些操作。
对于其他有同样问题的用户。这是我刚编的一个函数。
它不会在用户每次鼠标移动时运行,也不会在每次鼠标移动时清除计时器。
<script>
// Timeout in seconds
var timeout = 10; // 10 seconds
// You don't have to change anything below this line, except maybe
// the alert('Welcome back!') :-)
// ----------------------------------------------------------------
var pos = '', prevpos = '', timer = 0, interval = timeout / 5 * 1000;
timeout = timeout * 1000 - interval;
function mouseHasMoved(e){
document.onmousemove = null;
prevpos = pos;
pos = e.pageX + '+' + e.pageY;
if(timer > timeout){
timer = 0;
alert('Welcome back!');
}
}
setInterval(function(){
if(pos == prevpos){
timer += interval;
}else{
timer = 0;
prevpos = pos;
}
document.onmousemove = function(e){
mouseHasMoved(e);
}
}, interval);
</script>
我编写了一个小型ES6类来检测活动,并在空闲超时时触发事件。它涵盖了键盘,鼠标和触摸,可以激活和禁用,并且有一个非常精简的API:
const timer = new IdleTimer(() => alert('idle for 1 minute'), 1000 * 60 * 1);
timer.activate();
它不依赖于jQuery,不过您可能需要通过Babel来运行它以支持旧的浏览器。
https://gist.github.com/4547ef5718fd2d31e5cdcafef0208096