-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDelay.js
49 lines (43 loc) · 869 Bytes
/
Delay.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
import Raf from "./Raf";
import clamp from "./clamp";
/**
*
* An optimized implementation
* of window.setTimeout
*
* @param {Function} cb The callback to call after the delay.
* @param {Number} d The duration, in ms, of the delay.
* @returns {void}
* @example
*
* const d = 2000;
* const cb = () => console.log(`Call me ${d}ms later`);
*
* const delay = new Delay(cb, d);
* delay.run();
* delay.stop();
*
*/
function Delay(cb, d) {
this.d = d;
this.cb = cb;
this.loop = this.loop.bind(this);
this.rAF = new Raf(this.loop);
}
Delay.prototype = {
run: function() {
if (this.d === 0) this.cb();
else this.rAF.run();
},
stop: function() {
this.rAF.stop();
},
loop: function(e) {
var elapsed = clamp(e, 0, this.d);
if (elapsed === this.d) {
this.stop();
this.cb();
}
},
};
export default Delay;