Concurrent on fiber and requestIdleCallback
Fiber Concurrent mode basic
To make the update as small chunks, for requestIdleCallback
to use, React uses fiber nodes. Each fiber node can be a unitOfWork, and the workloop()
function iterates through all unit of work with scheduling.
let nextUnitOfWork = null
function workLoop(deadline) {
function enoughTime(){
return deadline.timeRemaining() >= 1;
}
while (nextUnitOfWork && enoughTime()) {
nextUnitOfWork = performUnitOfWork(
nextUnitOfWork
)
}
requestIdleCallback(workLoop)
}
requestIdleCallback(workLoop)
function performUnitOfWork(nextUnitOfWork) {
// TODO add dom node
// TODO create new fibers
// TODO return nextUnitOfWork (next visited fiber)
}
Key Concept
window.requestIdleCallback:
Similar to window.requestAnimationFrame
.
Pass a deadline
object to the callback, which contains a timeRemaining()
to calculate remain time
shim(just a shim, not polyfill) to explain the concept:
window.requestIdleCallback =
window.requestIdleCallback ||
function (cb) {
const start = new Date();
return setTimeout(function (){
cb({
didTimeout: false,
timeRemaining: function(){
const delta = new Date() - start;
return Math.max(0, 50 - delta);
}
});
}, 1);
}
window.cancelIdleCallback =
window.cancelIdleCallback ||
function (id) {
clearTimeout(id);
}
Key:
Use
setTimeout
to putcallback
to the end of main loop/thread, as a macro task, so that it is able to check thetimeRemain
after main loopReturn timeRemain ONLY when it's less than 50 ms, quoted as "When trying to maintain a responsive application, all responses to user interactions should be kept under 100ms. Should the user interact the 50ms window should, in most cases, allow for the idle callback to complete, and for the browser to respond to the user’s interactions."
Function returns
id
ofsetTimeout
, as a common pattern in JS event loop task handling, for program to callcancelIdleCallback
upon, this is used to just trying mocking the js schedule abilityQuote: "Ideally the work you do should be in small chunks (microtasks) that have relatively predictable characteristics." (nextUnitOfWork)
Ref:
https://pomb.us/build-your-own-react/
https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback
Last updated
Was this helpful?