在指定时间内没有来自用户的操作时Javascript超时 [英] Javascript timeout when no actions from user for specified time

查看:67
本文介绍了在指定时间内没有来自用户的操作时Javascript超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to call a js function when there is no activity from user on the web page for specified amount of time. If there is activity from user then reset timeout. I tried to search but couldn't find anything in particular. I am familiar with setTimeout() and clearTimeout() and how they work. What I am looking for is where/how to monitor for user activity. Is there any event in which I can set and clear timer?

谢谢。

编辑#1:

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

This webpage has one input text box & one button. It's kind of regular chat page. When I say no user activity, I mean that the user has not typed anything in text box or has not pressed any button for specified amount of time. And one more thing that it is targeted for touch based smartphone devices.

编辑#2:

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

Thank you everyone for suggestions. I've implemented solution based on more than one answers provided. So I will give upvote to all answers that I've found helpful instead of accepting one as answer.

推荐答案

// 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(){
  //...
}

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

Edit: Not using jQuery for whatever reason? Here's some (untested) code that should be cross-browser clean (to a point; doesn't work on IE5 Mac, for example ;):

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);
  }
} 

这篇关于在指定时间内没有来自用户的操作时Javascript超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆