-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathschedule.ts
55 lines (46 loc) · 1.29 KB
/
schedule.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { ITask } from './type'
const queue: ITask[] = []
const threshold: number = 5
const transitions: (() => void)[] = []
let deadline: number = 0
export const startTransition = cb => {
transitions.push(cb) && translate()
}
export const schedule = (callback: any): void => {
queue.push({ callback } as any)
startTransition(flush)
}
const task = (pending: boolean) => {
const cb = () => transitions.splice(0, 1).forEach(c => c())
if (!pending && typeof queueMicrotask !== 'undefined') {
return () => queueMicrotask(cb)
}
if (typeof MessageChannel !== 'undefined') {
const { port1, port2 } = new MessageChannel()
port1.onmessage = cb
return () => port2.postMessage(null)
}
return () => setTimeout(cb)
}
let translate = task(false)
const flush = (): void => {
deadline = getTime() + threshold
let job = peek(queue)
while (job && !shouldYield()) {
const { callback } = job
job.callback = null
const next = callback()
if (next) {
job.callback = next
} else {
queue.shift()
}
job = peek(queue)
}
job && (translate = task(shouldYield())) && startTransition(flush)
}
export const shouldYield = (): boolean => {
return getTime() >= deadline
}
export const getTime = () => performance.now()
const peek = (queue: ITask[]) => queue[0]