如何用JavaScript检测用户不活动

How to detect user inactivity with JavaScript?

本文关键字:用户 不活动 检测 JavaScript 何用      更新时间:2023-09-26

我试图有一个wordpress页面,登录你没有活动的时间间隔后的一定时间。现在我只是在测试"检测不活动并做点什么"的部分(关键部分)。我在这里找到了一些部分工作的代码;下面是代码:

<script>
var timeout;
document.onmousemove = function(){
clearTimeout(timeout);
timeout = setTimeout(function(){alert("move your mouse");}, 10000);
}
</script>

现在设置为每10秒发送一次警报,这样我就可以立即看到它正在工作(稍后会更长)。无论如何;当我在页面上运行这个时,它什么也不做。我可以在那里坐5分钟,什么也没发生。但如果我把这个标签留在浏览器中,它就会立即开始工作,如果没有像它应该做的那样的活动,它会每10秒发送一次警报。

但是如果我只是坐在那页上什么都不做,整个函数就不起作用了。有人能帮忙吗?谢谢…

试试这个:

function onInactive(ms, cb){
    var wait = setTimeout(cb, ms); 
    document.onmousemove = document.mousedown = document.mouseup = document.onkeydown = document.onkeyup = document.focus = function(){
        clearTimeout(wait);
        wait = setTimeout(cb, ms);
    };
}

JSFiddle:

http://jsfiddle.net/acNfy/4

你必须将你的移动悬停在右下角的窗口上,并保持不活动5秒才能看到结果:)

我喜欢在不活动发生时删除侦听器所以这是一个如何检测"无交互"的快速示例:

const IDLE_TIMEOUT = 5000; // in milliseconds
const idle_events = {
    load: false,
    mousemove: false,
    mousedown: false,
    touchstart: false,
    touchmove: false,
    keydown: false,
    click: false,
    scroll: true
}
let time;
function sendIdleEvent() {
    removeListeners()
    // Do something here
    // ...
}
function resetIdleTimeout() {
    clearTimeout(time)
    time = setTimeout(sendIdleEvent, IDLE_TIMEOUT)
}
function addListeners() {
    Object.entries(idle_events).forEach(([event_name, capture]) => {
        window.addEventListener(event_name, resetIdleTimeout, capture)
    })
}
function removeListeners() {
    Object.entries(idle_events).forEach(([event_name, capture]) => {
        window.removeEventListener(event_name, resetIdleTimeout, capture)
    })
}
addListeners()
resetIdleTimeout()

只需将IDLE_TIMEOUT值更改为您想要考虑的用户未交互的时间,并在sendIdleEvent函数中添加您需要做的任何事情。

添加或删除"听众";您可以准确地定义什么是"无交互"

我也会尝试在窗口加载时触发超时。

抱歉,之前的答案不完整。递归setTimeout可能就是你想要的。

(function interaction(){
    setTimeout(function(){
    // check for movement,
    if(movement...) {
        // if movement do nothing
        }
    else {
        interaction();

    },10000);
})();