-
Notifications
You must be signed in to change notification settings - Fork 0
/
time.js
73 lines (61 loc) · 1.64 KB
/
time.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
// So we can safely override these later
// See: http://www.adequatelygood.com/2011/4/Replacing-setTimeout-Globally
window.setTimeout = window.setTimeout;
window.clearTimeout = window.clearTimeout;
window.setInterval = window.setInterval;
window.clearInterval = window.clearInterval;
espionage.extend("time", function(e) {
var timers = [],
globalTime = 0,
resolveNamespace = espionage._util.resolveNamespace;
e.extendGlobals("wait", function(time) {
globalTime += time;
for (var i = 0; i < timers.length; i++) {
var timer = timers[i];
if (timer) {
if (timer.next <= globalTime) {
if (timer.repeat) {
do {
timer.fn.call();
timer.next += timer.time;
} while (timer.next <= globalTime);
} else {
timer.fn.call();
delete timers[i];
}
}
}
}
});
e.extendGlobals("setTimeout", function(fn, time) {
return generateTimer(fn, time, false);
});
e.extendGlobals("clearTimeout", function(id) {
return clearTimer(id);
});
e.extendGlobals("setInterval", function(fn, time) {
return generateTimer(fn, time, true);
});
e.extendGlobals("clearInterval", function(id) {
return clearTimer(id);
});
e.extendTeardown(function() {
timers = [];
globalTime = 0;
});
function generateTimer(fn, time, repeat) {
if (typeof fn === "string") {
fn = new Function(fn);
}
timers.push({
fn: fn,
time: time,
next: globalTime + time,
repeat: repeat
});
return timers.length - 1;
}
function clearTimer(id) {
delete timers[id];
}
});