forked from inexorabletash/polyfill
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtiming.js
85 lines (71 loc) · 2.42 KB
/
timing.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
77
78
79
80
81
82
83
84
85
(function(global) {
if (!('window' in global && 'document' in global))
return;
//----------------------------------------------------------------------
//
// Timing control for script-based animations
// https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/RequestAnimationFrame/Overview.html
//
//----------------------------------------------------------------------
// requestAnimationFrame - needed for IE9-
(function() {
if ('requestAnimationFrame' in global)
return;
var TARGET_FPS = 60,
requests = Object.create(null),
raf_handle = 0,
timeout_handle = -1;
function isVisible(element) {
return element.offsetWidth > 0 && element.offsetHeight > 0;
}
function onFrameTimer() {
var cur_requests = requests;
requests = Object.create(null);
timeout_handle = -1;
Object.keys(cur_requests).forEach(function(id) {
var request = cur_requests[id];
if (!request.element || isVisible(request.element))
request.callback(Date.now());
});
}
function requestAnimationFrame(callback, element) {
var cb_handle = ++raf_handle;
requests[cb_handle] = {callback: callback, element: element};
if (timeout_handle === -1)
timeout_handle = global.setTimeout(onFrameTimer, 1000 / TARGET_FPS);
return cb_handle;
}
function cancelAnimationFrame(handle) {
delete requests[handle];
if (Object.keys(requests).length === 0) {
global.clearTimeout(timeout_handle);
timeout_handle = -1;
}
}
global.requestAnimationFrame = requestAnimationFrame;
global.cancelAnimationFrame = cancelAnimationFrame;
}());
//----------------------------------------------------------------------
//
// Efficient Script Yielding
// https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/setImmediate/Overview.html
// (Not widely adopted.)
//
//----------------------------------------------------------------------
// setImmediate
(function() {
if ('setImmediate' in global)
return;
function setImmediate(callback/*, args*/) {
var params = [].slice.call(arguments, 1);
return global.setTimeout(function() {
callback.apply(null, params);
}, 0);
}
function clearImmediate(handle) {
global.clearTimeout(handle);
}
global.setImmediate = setImmediate;
global.clearImmediate = clearImmediate;
}());
}(this));