javascript / expert
Snippet
Macro-Task Scheduling via MessageChannel
MessageChannel is a high-performance alternative to setTimeout(0) for scheduling macro-tasks. Unlike setTimeout, which often suffers from a minimum 4ms delay (clamping) in nested calls, MessageChannel utilizes the browser's internal messaging system to execute tasks as soon as the current execution stack and micro-task queue are empty.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
function scheduleMacroTask(task) {const channel = new MessageChannel();channel.port1.onmessage = () => {channel.port1.close();task();};channel.port2.postMessage(null);}// Usage: Deferring non-critical executionscheduleMacroTask(() => {console.log('Processed in the next macro-task, bypassing 4ms clamping');});
nextjs
Breakdown
1
const channel = new MessageChannel();
Creates a new message channel with two connected ports for communication.
2
channel.port1.onmessage = () => { ... };
Sets up a handler that executes the task when a message is received on port 1.
3
channel.port2.postMessage(null);
Sends a message to port 2, triggering the micro-task to macro-task transition.