-
Notifications
You must be signed in to change notification settings - Fork 2
/
fromRequestFrame.ts
40 lines (34 loc) · 949 Bytes
/
fromRequestFrame.ts
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
import { Source } from '../index';
import { createSource } from './';
/**
* Create a source that emit a tick on request animation frame
*
* @param duration - in milliseconds, duration before stop request animation frame. If duration is 0 or not define, request animation frame will be stop only on unsubscribe
* @return callbag source
*
* @public
*/
function fromRequestFrame(duration?: number): Source<undefined> {
return createSource((next, complete) => {
let timeout = 0;
let requestFrame = 0;
const run = () => {
next(undefined);
requestFrame = requestAnimationFrame(run);
};
run();
if (duration) {
timeout = setTimeout(() => {
cancelAnimationFrame(requestFrame);
complete();
}, duration);
}
return () => {
cancelAnimationFrame(requestFrame);
if (duration) {
clearTimeout(timeout);
}
};
});
}
export default fromRequestFrame;