frejs / fre

:ghost: Tiny Concurrent UI library with Fiber.

Home Page:https://fre.deno.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Question] What kind of role do `unit` that in `scheduler` play?

SyMind opened this issue · comments

The following code may be the same. I'm not sure.

Origin:

export const schedule = (cb) => unit.push(cb) === 1 && postMessage()

const postMessage = (() => {
  const cb = () => unit.splice(0, unit.length).forEach((c) => c())
  if (typeof MessageChannel !== 'undefined') {
    const { port1, port2 } = new MessageChannel()
    port1.onmessage = cb
    return () => port2.postMessage(null)
  }
  return () => setTimeout(cb)
})()

After:

export const schedule = cb => {
  if (typeof MessageChannel !== 'undefined') {
    const { port1, port2 } = new MessageChannel()
    port1.onmessage = cb
    port2.postMessage(null)
  } else {
    setTimeout(cb)
  }
}

因为有时候在执行 flushwork 的同时,会push进来 effects,为了保证 effects 在当前组件的 flushwork 后执行,所以使用了一个小队列,也就是 unit

啊哈,明白了!微任务之前有可能 push 进其他任务。