”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何在 JavaScript 中检测用户空闲时间?

如何在 JavaScript 中检测用户空闲时间?

发布于2024-12-21
浏览:414

How Can I Detect User Idle Time in JavaScript?

检测 JavaScript 中的空闲时间

简介:

在 Web 开发中,了解用户活动对于优化性能和提供更好的用户体验至关重要。检测空闲时间(定义为不活动或 CPU 使用率较低的时间段)可以帮助您触发预加载内容或用户身份验证等操作。

JavaScript 实现:

检测在 JavaScript 中空闲时,您可以使用以下普通 JavaScript 方法:

代码片段:

var inactivityTime = function () {
    var time;
    window.onload = resetTimer;
    // DOM Events
    document.onmousemove = resetTimer;
    document.onkeydown = resetTimer;

    function logout() {
        alert("You are now logged out.")
        //location.href = 'logout.html'
    }

    function resetTimer() {
        clearTimeout(time);
        time = setTimeout(logout, 3000)
        // 1000 milliseconds = 1 second
    }
};

用法:

要初始化空闲时间检测,请在页面加载后调用 inactivityTime() 函数:

window.onload = function() {
  inactivityTime();
}

自定义:

您可以添加更多 DOM 事件来监控用户活动。一些最常用的事件是:

document.onload = resetTimer;
document.onmousemove = resetTimer;
document.onmousedown = resetTimer; // touchscreen presses
document.ontouchstart = resetTimer;
document.onclick = resetTimer;     // touchpad clicks
document.onkeydown = resetTimer;   // onkeypress is deprectaed
document.addEventListener('scroll', resetTimer, true); // improved; see comments

为了更好的定制,可以使用数组来注册多个事件:

window.addEventListener('load', resetTimer, true);
var events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'];
events.forEach(function(name) {
 document.addEventListener(name, resetTimer, true);
});

通过自定义您监视的事件,您可以定制空闲时间检测以满足您的特定应用程序的需求。

最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3