-
Notifications
You must be signed in to change notification settings - Fork 0
/
rAFPolyfill.js
83 lines (72 loc) · 2.73 KB
/
rAFPolyfill.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
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
// requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
// MIT license
'use strict';
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
var rAF, cAF;
if (typeof window === 'object') {
rAF = window.requestAnimationFrame;
cAF = window.cancelAnimationFrame || window.cancelRequestAnimationFrame;
for (var x = 0; x < vendors.length && !rAF; ++x) {
rAF = window[vendors[x] + 'RequestAnimationFrame'];
cAF = window[vendors[x] + 'CancelRequestAnimationFrame'] ||
window[vendors[x] + 'CancelAnimationFrame'];
}
if (rAF && !cAF) {
// cAF not supported.
// Fall back to setInterval for now (very rare).
rAF = null;
}
}
if (!rAF) {
var now = Date.now ? Date.now : function () {
return new Date().getTime();
};
rAF = function(callback) {
var currTime = now();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = setTimeout(function () {
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
cAF = function (id) {
clearTimeout(id);
};
}
var animationFrame = {
/**
* Cross browser version of [requestAnimationFrame]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame}.
*
* Used by Engine in order to establish a render loop.
*
* If no (vendor prefixed version of) `requestAnimationFrame` is available,
* `setTimeout` will be used in order to emulate a render loop running at
* approximately 60 frames per second.
*
* @method requestAnimationFrame
*
* @param {Function} callback function to be invoked on the next frame.
* @return {Number} requestId to be used to cancel the request using
* {@link cancelAnimationFrame}.
*/
requestAnimationFrame: rAF,
/**
* Cross browser version of [cancelAnimationFrame]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/cancelAnimationFrame}.
*
* Cancels a previously using [requestAnimationFrame]{@link animationFrame#requestAnimationFrame}
* scheduled request.
*
* Used for immediately stopping the render loop within the Engine.
*
* @method cancelAnimationFrame
*
* @param {Number} requestId of the scheduled callback function
* returned by [requestAnimationFrame]{@link animationFrame#requestAnimationFrame}.
*/
cancelAnimationFrame: cAF
};
module.exports = animationFrame;