-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathidle-monitor.js
76 lines (65 loc) · 2.4 KB
/
idle-monitor.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
(function(factory) {
if (typeof define === "function" && define.amd) {
define(["backbone", "underscore"], factory);
}
}(function(Backbone, _) {
var LOCAL_STORAGE_KEY = "IdleMonitor.actionTime";
function IdleMonitor(options) {
_.extend(this, Backbone.Events);
this.timeout = null;
this.lastAction = null;
this.warningFired = false;
this.options = _.defaults(options || {}, {
"checkIntervalSecs" : 10,
"events" : {
"document" : "click keyup"
},
"warningSecs" : 60 * 14,
"timeoutSecs" : 60 * 15
});
// Apply action callbacks
_.each(_.keys(this.options.events), _.bind(function(selector) {
var s = (selector === "document" ? document : selector);
Backbone.$(s).on(this.options.events[selector], _.bind(this.actionCallback, this));
}, this));
}
IdleMonitor.prototype.actionCallback = function() {
localStorage.setItem(LOCAL_STORAGE_KEY, (new Date()).getTime());
this.trigger("action");
};
IdleMonitor.prototype.checkCallback = function() {
var lastActionUnixTime = parseInt(localStorage.getItem(LOCAL_STORAGE_KEY), 10),
timeDiff = ((new Date()).getTime() - (new Date(lastActionUnixTime)).getTime()) / 1000;
// Store the last time an action happened
if (this.lastAction && this.lastAction !== lastActionUnixTime) {
this.trigger("action");
this.warningFired = false;
this.lastAction = lastActionUnixTime;
return;
}
this.lastAction = lastActionUnixTime;
// Fire warning
if (!this.warningFired && timeDiff >= this.options.warningSecs) {
this.trigger("warning");
this.warningFired = true;
}
// Fire timeout
if (timeDiff >= this.options.timeoutSecs) {
this.trigger("timeout");
}
};
IdleMonitor.prototype.start = function() {
this.stop();
this.actionCallback();
this.timeout = setInterval(_.bind(this.checkCallback, this),
this.options.checkIntervalSecs * 1000);
};
IdleMonitor.prototype.stop = function() {
if (this.timeout) {
clearTimeout(this.timeout);
this.timeout = null;
}
this.warningFired = false;
};
return IdleMonitor;
}));