score:16

Accepted answer

They use postMessage (in combination with requestAnimationFrame):

  // We use the postMessage trick to defer idle work until after the repaint.

Found in React/scheduler/src/forks/SchedulerHostConfig.default.js

setTimeout can't be used as it will be throttled if used recursively. requestAnimationFrame can't be used by itself as that gets triggered right before the repaint. Now if you however post a message to the page itself right before the repaint using postMessage, then that callback will run directly after the repaint.

 const channel = new MessageChannel();

 channel.port1.onmessage = function() {
  console.log("after repaint");
 };

 requestAnimationFrame(function () {
   console.log("before repaint");
   channel.port2.postMessage(undefined);
 });

Related Query

More Query from same tag