javascript / expert
Snippet
Breaking Long Tasks with scheduler.yield
Modern browser schedulers provide scheduler.yield() to break up long-running JavaScript tasks. Unlike setTimeout(0), it prioritizes finishing the current workflow while still allowing the browser to handle critical UI interactions and rendering frames, preventing 'Jank'.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
async function processLargeDataset(data) {for (let i = 0; i < data.length; i++) {performHeavyCalculation(data[i]);if (i % 50 === 0 && 'scheduler' in window) {// Yield control back to the main threadawait scheduler.yield();}}}function performHeavyCalculation(item) {const start = performance.now();while (performance.now() - start < 5) {} // Simulate 5ms work}
nextjs
Breakdown
1
await scheduler.yield()
Pauses execution to let the browser process pending high-priority tasks like input events.
2
if (i % 50 === 0)
Strategic yielding every 50 iterations to balance throughput and responsiveness.