简体   繁体   English

如何使用JavaScript检测用户不活动?

[英]How to detect user inactivity with JavaScript?

I am trying to have a wordpress page that logs you out with no activity after a certain interval of time. 我正在尝试建立一个wordpress页面,该页面在一定时间间隔后将您注销,并且没有任何活动。 Right now I am just testing the "detect inactivity and do something" part of this (the key part). 现在,我只是在测试“检测不活动并执行某些操作”部分(关键部分)。 I found some code on here that partially works; 我在这里找到了部分起作用的代码。 here is the code: 这是代码:

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

It is set right now to send that alert every 10 seconds just so I can see immediately it is working (will be much longer later). 现在设置为每10秒发送一次警报,以便我可以立即看到它正在运行(以后会更长)。 Anyway; 无论如何; when i run this on a page it does nothing. 当我在页面上运行它时,它什么也没做。 I can sit there for 5 minutes and nothing happens. 我可以坐在那里5分钟,什么也没发生。 But if I leave that tab in my browser, it immediately starts working and sends the alert every 10 seconds if no activity like it is supposed to. 但是,如果我将该标签留在浏览器中,它将立即开始工作,并且如果没有应有的活动,则每10秒发送一次警报。

But the whole function does not work if I just sit there on that page and do nothing. 但是如果我只是坐在那页上什么都不做,那么整个功能将无法正常工作。 Can anyone help with this? 有人能帮忙吗? Thanks... 谢谢...

Try this instead: 尝试以下方法:

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: 的jsfiddle:

http://jsfiddle.net/acNfy/4 http://jsfiddle.net/acNfy/4

You will have to hover your move on the lower right window and stay inactive for 5 seconds to see the results :) 您必须将鼠标悬停在右下角的窗口上,并保持不活动状态5秒钟才能看到结果:)

I would try firing the timeout on window load too. 我也会尝试在窗口加载时触发超时。

apologies, for the incomplete answer before. 抱歉,对于之前的不完整答案。 A recursive setTimeout might be what you are looking for. 递归setTimeout可能是您想要的。

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



    },10000);

})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM