-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcleanupRequestAnimationFrame.ts
More file actions
43 lines (37 loc) · 1.04 KB
/
Copy pathcleanupRequestAnimationFrame.ts
File metadata and controls
43 lines (37 loc) · 1.04 KB
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
import lodash from "lodash";
import { Disposer } from "../types/disposer";
const { isFunction } = lodash;
/**
* Setup/cleanup wrapper for requestAnimationFrame.
* On rerun, the previous frame is cancelled and its cleanup runs.
* @param cb - function called in the animation frame; may return an optional cleanup function.
* @returns function for cancelling the requested frame and running cleanup.
*
* @example
* const dispose = cleanupRequestAnimationFrame(() => {
* // animation code
* return () => {
* // optional cleanup
* }
* })
*
* // Cancel and clean up:
* dispose()
*/
export function cleanupRequestAnimationFrame(cb: () => Disposer): () => void {
let dispose: void | (() => void);
let isCancelled = false;
function innerCb() {
if (isCancelled) {
return;
}
const effect = cb();
dispose = isFunction(effect) ? effect : undefined;
}
const animationFrameId = requestAnimationFrame(innerCb);
return () => {
isCancelled = true;
dispose?.();
cancelAnimationFrame(animationFrameId);
};
}