How React Cooperates Scheduling With The Browser
requestIdleCallback(myNonEssentialWork);
function myNonEssentialWork (deadline) {
while (deadline.timeRemaining() > 0 && tasks.length > 0)
doWorkIfNeeded();
if (tasks.length > 0)
requestIdleCallback(myNonEssentialWork);
}
var eventsToSend = [];
function onNavClick () {
eventsToSend.push(
{
category: 'button',
action: 'click',
label: 'nav',
value: 'open'
});
schedulePendingEvents();
}
function schedulePendingEvents() {
requestIdleCallback(
processPendingAnalyticsEvents,
{ timeout: 2000 }
);
}
Example: Sending Analytic Events
function processPendingAnalyticsEvents (deadline) {
while (deadline.timeRemaining() > 0 && eventsToSend.length > 0) {
var evt = eventsToSend.pop();
ga('send', 'event',
evt.category,
evt.action,
evt.label,
evt.value);
}
if (eventsToSend.length > 0)
schedulePendingEvents();
}
RequestIdleCallback allowed us to ....
React uses this flow (almost exactly) to schedule units of work. Neat.