summaryrefslogtreecommitdiff
path: root/packages/webapi/src/lib/AnimationFrame.ts
blob: e29d3cabf7baef62897faf8ac4c39502dfbefd40 (plain) (blame)
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
import {
	clearTimeout as nodeClearTimeout,
	setTimeout as nodeSetTimeout,
} from 'node:timers'
import * as _ from './utils.js'

const INTERNAL = { tick: 0, pool: new Map() }

export function requestAnimationFrame<
	TArgs extends any[],
	TFunc extends (...args: TArgs) => any
>(callback: TFunc): number {
	if (!INTERNAL.pool.size) {
		nodeSetTimeout(() => {
			const next = _.__performance_now()

			for (const func of INTERNAL.pool.values()) {
				func(next)
			}

			INTERNAL.pool.clear()
		}, 1000 / 16)
	}

	const func = _.__function_bind(callback, undefined)
	const tick = ++INTERNAL.tick

	INTERNAL.pool.set(tick, func)

	return tick
}

export function cancelAnimationFrame(requestId: number): void {
	const timeout = INTERNAL.pool.get(requestId)

	if (timeout) {
		nodeClearTimeout(timeout)

		INTERNAL.pool.delete(requestId)
	}
}