javascript / expert
Snippet
Micro-Task Scheduling via MessageChannel API
This schedules a task to run immediately after the current script execution and before the next paint. Unlike setTimeout(0), MessageChannel tasks are treated with higher priority by the browser and avoid the minimum 4ms delay.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
const scheduleDeferredTask = (task) => {const channel = new MessageChannel();channel.port1.onmessage = () => {task();channel.port1.close();};channel.port2.postMessage(null);};// Usage in Reactconst handleHeavyOp = () => {scheduleDeferredTask(() => compute(data));};
react
Breakdown
1
const channel = new MessageChannel();
Creates a two-way communication pipe for asynchronous messaging.
2
channel.port1.onmessage = () => { task(); ... }
Defines the task to be executed when the message is received.
3
channel.port2.postMessage(null);
Triggers the message asynchronously, yielding control back to the event loop temporarily.