在指定时间内没有来自用户的操作时Javascript超时

ind*_*ull 15 javascript timeout

我想在网页上没有来自用户的活动指定的时间内调用js函数.如果有来自用户的活动,则重置超时.我试图搜索,但没有找到任何特别的东西.我熟悉setTimeout()和clearTimeout()以及它们是如何工作的.我在寻找的是在哪里/如何监控用户活动.有没有可以设置和清除计时器的事件?

谢谢.

编辑#1:

该网页有一个输入文本框和一个按钮.这是一种常规的聊天页面.当我说没有用户活动时,我的意思是用户没有在文本框中输入任何内容,或者没有在指定的时间内按任何按钮.还有一件事是它针对基于触摸的智能手机设备.

编辑#2:

谢谢大家的建议.我已根据提供的多个答案实施了解决方案.因此,我会放弃对我发现有帮助的所有答案的投票,而不是接受一个答案.

Phr*_*ogz 27

// Using jQuery (but could use pure JS with cross-browser event handlers):
var idleSeconds = 30;

$(function(){
  var idleTimer;
  function resetTimer(){
    clearTimeout(idleTimer);
    idleTimer = setTimeout(whenUserIdle,idleSeconds*1000);
  }
  $(document.body).bind('mousemove keydown click',resetTimer); //space separated events list that we want to monitor
  resetTimer(); // Start the timer when the page loads
});

function whenUserIdle(){
  //...
}
Run Code Online (Sandbox Code Playgroud)

编辑:出于什么原因不使用jQuery?这里有一些(未经测试的)代码应该是跨浏览器清理的(例如;在IE5 Mac上不起作用;):

attachEvent(window,'load',function(){
  var idleSeconds = 30;
  var idleTimer;
  function resetTimer(){
    clearTimeout(idleTimer);
    idleTimer = setTimeout(whenUserIdle,idleSeconds*1000);
  }
  attachEvent(document.body,'mousemove',resetTimer);
  attachEvent(document.body,'keydown',resetTimer);
  attachEvent(document.body,'click',resetTimer);

  resetTimer(); // Start the timer when the page loads
});

function whenUserIdle(){
  //...
}

function attachEvent(obj,evt,fnc,useCapture){
  if (obj.addEventListener){
    obj.addEventListener(evt,fnc,!!useCapture);
    return true;
  } else if (obj.attachEvent){
    return obj.attachEvent("on"+evt,fnc);
  }
} 
Run Code Online (Sandbox Code Playgroud)


Way*_*ett 9

这需要一个去抖者:

function debounce(callback, timeout, _this) {
    var timer;
    return function(e) {
        var _that = this;
        if (timer)
            clearTimeout(timer);
        timer = setTimeout(function() { 
            callback.call(_this || _that, e);
        }, timeout);
    }
}
Run Code Online (Sandbox Code Playgroud)

像这样使用:

// we'll attach the function created by "debounce" to each of the target
// user input events; this function only fires once 2 seconds have passed
// with no additional input; it can be attached to any number of desired
// events
var userAction = debounce(function(e) {
    console.log("silence");
}, 2000);

document.addEventListener("mousemove", userAction, false);
document.addEventListener("click", userAction, false);
document.addEventListener("scroll", userAction, false);
Run Code Online (Sandbox Code Playgroud)

第一个用户操作(mousemove,click或scroll)启动一个函数(附加到计时器),每次发生另一个用户操作时都会重置.在没有操作的指定时间过去之前,主要回调不会触发.

请注意,不需要全局标志或超时变量.全局范围仅接收您的去抖回调.谨防需要维护全球状态的解决方案 ; 在更大的应用程序环境中,它们很难被推理.

另请注意,此解决方案完全是通用的.请注意仅适用于极其狭窄的用例的解决方案.

  • 在你看到"矫枉过正"的地方,我看到了一个概括. (5认同)

sdl*_*rhc 5

大多数JavaScript事件都会冒泡,因此您可以执行以下操作:

  • 拿出你会认为是"从用户活动"的所有事件的列表(例如,click,mousemove,keydown,等)
  • 将一个函数作为所有这些事件的事件监听器附加到document(或者document.body对于其中一些事件;我不记得这是否是一个问题).
  • 当侦听器被触发时,让它用clearTimeout/ 重置计时器setTimeout

所以你最终得到这样的东西:

var events = ['click', 'mousemove', 'keydown'],
    i = events.length,
    timer,
    delay = 10000,
    logout = function () {
        // do whatever it is you want to do
        // after a period of inactivity
    },
    reset = function () {
        clearTimeout(timer);
        timer = setTimeout(logout, 10000);
    };

while (i) {
    i -= 1;
    document.addEventListener(events[i], reset, false);
}
reset();
Run Code Online (Sandbox Code Playgroud)

请注意,您必须使用上述代码解决一些问题:

  • 它不是跨浏览器兼容的.它只使用addEventListener,因此在IE6-8中不起作用
  • 它会污染全局命名空间.它会创建许多可能与其他脚本冲突的多余变量.

它更能让您了解自己可以做些什么.

现在还有其他四个答案,但我已经把它全部输了,所以那里:P


gil*_*ly3 3

您希望在文档级别监视mousemovekeypresskeydown和/或 等事件。click

编辑:这是一个智能手机应用程序会改变您想要监听的事件。考虑到您的文本框和按钮要求,我会听取oninput并添加resetTimeout()对按钮的单击处理程序的调用。

var inactivityTimeout = 0;
function resetTimeout() {
    clearTimeout(inactivityTimeout);
    inactivityTimeout = setTimeout(inactive, 300000);
}
function inactive() {
   ...
}
document.getElementById("chatInput").oninput = resetTimeout;
Run Code Online (Sandbox Code Playgroud)