如何准确地检测JavaScript中的空闲时间?是否有可能发现“闲散“是JavaScript时间吗?我的主要用例可能是预取或预加载内容。空闲时间:用户不活动或未使用任何cpu的期间
3 回答
扬帆大鱼
TA贡献1799条经验 获得超9个赞
function idleLogout() {
var t;
window.onload = resetTimer;
window.onmousemove = resetTimer;
window.onmousedown = resetTimer; // catches touchscreen presses as well
window.ontouchstart = resetTimer; // catches touchscreen swipes as well
window.onclick = resetTimer; // catches touchpad clicks as well
window.onkeypress = resetTimer;
window.addEventListener('scroll', resetTimer, true); // improved; see comments
function yourFunction() {
// your function for too long inactivity goes here
// e.g. window.location.href = 'logout.php';
}
function resetTimer() {
clearTimeout(t);
t = setTimeout(yourFunction, 10000); // time is in milliseconds
}}idleLogout();.
除了在活动检测方面的改进,以及document到window,这个脚本实际上调用了函数,而不是让它无所事事。
它不会直接捕获零CPU使用率,但这是不可能的,因为执行一个函数会导致CPU使用。而用户的不活动最终导致了零CPU的使用,因此它间接地捕捉到零CPU的使用。
添加回答
举报
0/150
提交
取消
