Line data Source code
1 : type RenderLoopOptions = {
2 : tick: () => void
3 : isActive: () => boolean
4 : }
5 :
6 : export type RenderLoopHandle = {
7 : stop: () => void
8 : wake: () => void
9 : }
10 :
11 27 : export function startRenderLoop({
12 : tick,
13 : isActive
14 : }: RenderLoopOptions): RenderLoopHandle {
15 27 : let frameId: number | null = null
16 27 : let stopped = false
17 :
18 27 : const loop = () => {
19 456 : frameId = null
20 456 : if (!isActive()) return
21 426 : frameId = requestAnimationFrame(loop)
22 426 : tick()
23 : }
24 :
25 27 : loop()
26 :
27 27 : return {
28 : stop() {
29 1 : stopped = true
30 1 : if (frameId !== null) {
31 1 : cancelAnimationFrame(frameId)
32 1 : frameId = null
33 : }
34 : },
35 : wake() {
36 34 : if (stopped || frameId !== null) return
37 14 : frameId = requestAnimationFrame(loop)
38 : }
39 : }
40 : }
|