-
Notifications
You must be signed in to change notification settings - Fork 6
/
hackemtimer.js
55 lines (50 loc) · 1.55 KB
/
hackemtimer.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
/*
Welcome to a Hacker News Bookmarklet...
"Hack'em Up" by Mr Speaker
v1.1
Timer module: Will only update when tab is focused.
*/
var hnutimer = {
refreshTime: 2 * (60 * 1000),
waitOnFocusTime: 1500,
timerId: null,
lastCheck: null,
focusedTime: null,
init: function(onTimerExpire) {
$(window).bind({
"focus": function(){ hnutimer.onFocus(); },
"blur": function(){ hnutimer.onBlur(); }
});
this.onTimerExpire = onTimerExpire;
// Init onfocus to avoid first time load delay
this.focusedTime = new Date().getTime() - this.waitOnFocusTime;
this.update();
},
update: function() {
var doFetch = true,
refreshTime = this.refreshTime,
previous = this.lastCheck,
rightNow = new Date().getTime(),
elapsed = previous ? rightNow - previous : refreshTime;
if (elapsed < refreshTime) {
doFetch = false;
refreshTime -= elapsed;
}
if(doFetch) {
if(rightNow - this.focusedTime >= this.waitOnFocusTime){
this.onTimerExpire && this.onTimerExpire();
this.lastCheck = rightNow;
} else {
refreshTime = this.waitOnFocusTime;
}
}
this.timerId = setTimeout(function(){ hnutimer.update(); }, refreshTime);
},
onFocus: function() {
this.focusedTime = new Date().getTime();
this.update();
},
onBlur: function() {
clearTimeout(this.timerId);
}
};