1. React Source Code
1.1. jsx
const queue = [];
const threshold = 1000 / 60;
const transtions = [];
let deadline = 0;
const now = () => performance.now();
const peek = arr => arr.length === 0 ? null : arr[0];
export function schedule (cb) {
queue.push(cb);
startTranstion(flush);
}
function shouldYield() {
return navigator.scheduling.isInputPending() || now() >= deadline;
}
function startTranstion(cb) {
transtions.push(cb) && postMessage();
}
const postMessage = (() => {
const cb = () => transtions.splice(0, 1).forEach(c => c());
const { port1, port2 } = new MessageChannel();
port1.onmessage = cb;
return () => port2.postMessage(null);
})()
function flush() {
deadline = now() + threshold;
let task = peek(queue);
while(task && !shouldYield()) {
const { cb } = task;
const next = cb();
if(next && typeof next === "function") {
task.cb = next;
} else {
queue.shift()
}
task = peek(queue);
}
task && startTranstion(flush)
}
1.2. requestIdleCallback
- requestIdleCallback(RIC)
- 50毫秒问题
- postMessage: messageChannel event-loop
- setTimeout: 有4到5秒的延迟
1.3. scheduler
- generator:无法从中间位置开始
- web-worker: 无法处理 dom
1.4. useTransition
1.5. Future