我需要知道是否在10秒内没有键盘按下或者鼠标点击操作,如果是,则显示一个警示窗口。如果使用jquery比纯js更有效率,我可以使用jquery。
该怎样实现呢?谢谢。
该怎样实现呢?谢谢。
像这样的:
(function(){
var timer;
function resetTimer(){
clearTimeout(timer);
timer = setTimeout(function(){
alert('No keydown for 10 seconds');
// Call reset timer here if you want the timer to start again
// when the alert is closed
// Otherwise, if you want to stop the timer forever,
// remove the event handler from document.onkeydown
}, 10000);
}
resetTimer();
document.onkeydown = resetTimer;
})();
这段代码假设您没有绑定其他内容到文档的 keydown 监听器。如果您已经绑定了其他内容,则应改用 addEventListener
和 attachEvent
。
resetTimer()
可以每秒执行约350,000次。如果有人能打字那么快,那就太可怕了:P。好处是当用户空闲时,它也处于空闲状态,而不会在用户空闲时占用(虽然很小的)CPU。 - Paulvar seconds = 0;
window.setInterval(function() {
seconds++;
if(seconds == 10) {
alert("No keydown or click in 10 seconds");
}
}, 1000);
$('body').live('click keydown', function(e) {
e.preventDefault();
seconds = 0;
});
必须具备jQuery。
var action_happened = false;
!action_happened
,则显示一个警报。action_happened = true;
action_happened = true;
之后,删除点击/按键处理程序。这是可选的,即使没有这一步也足够高效。