-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFrame.js
97 lines (77 loc) · 1.88 KB
/
Frame.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
86
87
88
89
90
91
92
93
94
95
96
97
/**
* @author Aaron Clinger - https://github.com/aaronclinger/frame.js
*/
(function(window) {
'use strict';
function Frame() {
var pub = {};
var updates = [];
var isUpdating = false;
pub.addFrameUpdate = function(options) {
if (typeof(options) === 'function') {
options = {callback: options};
}
var fps = Math.min(60, options.fps || 60);
updates.push({
time: Date.now(),
delay: (fps === 60) ? 0 : Math.floor(1000 / fps),
repeat: options.repeat || -1,
callback: options.callback
});
if ( ! isUpdating) {
isUpdating = true;
window.requestAnimationFrame(onFrame);
}
};
pub.removeFrameUpdate = function(fn) {
var len = updates.length;
while (len--) {
if (fn === updates[len].callback) {
updates.splice(len, 1);
return true;
}
}
return false;
};
var onFrame = function() {
var now = Date.now();
var len = updates.length;
var item;
var diff;
while (len--) {
item = updates[len];
diff = now - item.time;
if (item.delay === 0 || diff >= item.delay) {
item.time = now;
item.callback();
if (item.repeat !== -1 && --item.repeat === 0) {
pub.removeFrameUpdate(item.callback);
}
}
}
if (updates.length) {
window.requestAnimationFrame(onFrame);
} else {
isUpdating = false;
}
};
if ( ! window.requestAnimationFrame) {
window.requestAnimationFrame = (function() {
return window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 17);
};
})();
}
if ( ! Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
return pub;
}
window.Frame = new Frame();
}(window));