-
Notifications
You must be signed in to change notification settings - Fork 7
/
PeriodicalExecuter.js
64 lines (46 loc) · 1.13 KB
/
PeriodicalExecuter.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
/*
Script: PeriodicalExecuter.js
port of the Prototype.js timer to Mootools
License: MIT-style license.
Copyright: Copyright (c) 2007 Thierry bela <bntfr at yahoo dot fr>
License:
MIT-style license.
Authors:
Thierry Bela
TODO: possibility to stop the timer when the window is idle ?
*/
var PeriodicalExecuter = new Class({
// name: 'PeriodicalExecuter',
initialize: function(callback, frequency) {
this.callback = callback;
this.frequency = frequency;
this.currentlyExecuting = false;
this.registerCallback()
},
registerCallback: function() {
this.stop();
this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
return this
},
execute: function() {
this.callback(this);
return this
},
stop: function() {
if (!this.timer) return this;
clearInterval(this.timer);
this.timer = null;
return this
},
onTimerEvent: function() {
if (!this.currentlyExecuting) {
try {
this.currentlyExecuting = true;
this.execute();
} finally {
this.currentlyExecuting = false;
}
}
return this
}
});