Skip to content

Commit

Permalink
feat(schedule): scheduler uses macroTasks when possible
Browse files Browse the repository at this point in the history
  • Loading branch information
kolodziejczak-sz committed Sep 23, 2021
1 parent 3fc7b13 commit be42f69
Showing 1 changed file with 19 additions and 7 deletions.
26 changes: 19 additions & 7 deletions src/schedule.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,42 @@
import { IFiber, ITask, ITaskCallback } from "./type"
import { options } from "./reconcile"

const queue: ITask[] = []
const threshold: number = 1000 / 60
const transitions = []
let deadline: number = 0

export const startTransition = (cb) => {
transitions.push(cb) && postMessage()
transitions.push(cb) && runTransition()
}

export const schedule = (callback: any): void => {
queue.push({ callback } as any)
startTransition(flush)
}

const postMessage = (() => {
const transitionRunnerFactory = (useMicrotasks: boolean) => {
const cb = () => transitions.splice(0, 1).forEach((c) => c())

if (useMicrotasks) {
if (typeof queueMicrotask !== "undefined") {
return () => queueMicrotask(cb)
}
const resolvedPromise = Promise.resolve()
return () => resolvedPromise.then(cb)
}

if (typeof MessageChannel !== "undefined") {
const { port1, port2 } = new MessageChannel()
port1.onmessage = cb
return () => port2.postMessage(null)
}
return () => setTimeout(cb)
})()
}

const runTransitionAsTask = transitionRunnerFactory(false)
const runTransitionAsMicroTask = transitionRunnerFactory(true)

let runTransition = runTransitionAsMicroTask

const flush = (): void => {
deadline = getTime() + threshold
Expand All @@ -44,10 +56,10 @@ const flush = (): void => {
}

export const shouldYield = (): boolean => {
if (options.sync) return false
return (
const isInputPending =
(navigator as any)?.scheduling?.isInputPending() || getTime() >= deadline
)
runTransition = isInputPending ? runTransitionAsTask : runTransitionAsMicroTask
return isInputPending
}

export const getTime = () => performance.now()
Expand Down

0 comments on commit be42f69

Please sign in to comment.