CPU work and latency
Local practice: Node.js 22.16.0 on Linux x64; proposed teaching baseline 26.13.1 remains untested. Copy only the listed files into a fresh disposable directory. No dependency installation or external services required. These are static Node.js examples, not verified ByteMind runner tasks.
Observe an async function doing synchronous computation
async function sum() { let value = 0; for (let i = 1; i <= 100; i++) value += i; console.log('sum', value);}const done = sum();console.log('returned');await done;Run:
node main.mjsExpected stdout:
sum 5050returnedExit status: 0. Expected stderr: empty.
How it works
Break a modest calculation into bounded chunks and yield between them if responsiveness matters. Awaiting a resolved promise yields to microtasks but does not guarantee a turn for I/O. Awaiting the promise version of setImmediate between chunks gives the event loop an opportunity to progress. For substantial CPU work, consider a bounded worker_threads pool or separate service, taking serialization, memory, failure and cancellation into account. A worker thread is not a security sandbox. Measure event-loop delay and workload throughput before optimizing; the fixtures only establish ordering, not performance.
Yield between bounded calculation chunks
import { setImmediate as yieldTurn } from 'node:timers/promises';let total = 0;for (let start = 1; start <= 12; start += 4) { for (let n = start; n < start + 4; n++) total += n; console.log('chunk', start); await yieldTurn();}console.log('total', total);Run:
node main.mjsExpected stdout:
chunk 1chunk 5chunk 9total 78Exit status: 0. Expected stderr: empty.
Common mistake
Marking a CPU-heavy function async does not interrupt the synchronous body. Avoid unbounded chunk counts and tiny yields that dominate useful work. Do not increase native pool size to solve main-thread CPU starvation.
Practice
Modify the chunk size to four and explain the trade-off between yield frequency and overhead. Keep the work finite; compare the exact result before and after partitioning.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
CPU work and latency — knowledge check
Apply the concepts and predict the behavior taught in this lesson.
Where does the loop in the first async function execute?
Why use an immediate promise between chunks?
Which approach can provide actual CPU parallelism for substantial JS computation?