我最近刚刚做了这样的事情,虽然使用 Prototype 而不是 JQuery,但我想只要 JQuery 支持自定义事件,实现就会大致相同。
简而言之,IdleMonitor 是一个观察鼠标和键盘事件的类(根据您的需要进行相应调整)。每 30 秒它重置计时器并广播一个 state:idle 事件,除非它获得鼠标/键事件,在这种情况下它广播一个 state:active 事件。
var IdleMonitor = Class.create({
debug: false,
idleInterval: 30000, // idle interval, in milliseconds
active: null,
initialize: function() {
document.observe("mousemove", this.sendActiveSignal.bind(this));
document.observe("keypress", this.sendActiveSignal.bind(this));
this.timer = setTimeout(this.sendIdleSignal.bind(this), this.idleInterval);
},
// use this to override the default idleInterval
useInterval: function(ii) {
this.idleInterval = ii;
clearTimeout(this.timer);
this.timer = setTimeout(this.sendIdleSignal.bind(this), ii);
},
sendIdleSignal: function(args) {
// console.log("state:idle");
document.fire('state:idle');
this.active = false;
clearTimeout(this.timer);
},
sendActiveSignal: function() {
if(!this.active){
// console.log("state:active");
document.fire('state:active');
this.active = true;
this.timer = setTimeout(this.sendIdleSignal.bind(this), this.idleInterval);
}
}
});
然后我刚刚创建了另一个类,其中包含以下内容:
Event.observe(document, 'state:idle', your-on-idle-functionality);
Event.observe(document, 'state:active', your-on-active-functionality)