Blocking and Non-blocking Code
Blocking code stops everything until it finishes. Non-blocking code starts work and lets other code run while it waits.
Blocking code
This loop waits about 100 milliseconds. Node does nothing else while it waits.
const start = Date.now();
while (Date.now() - start < 100) {}
console.log("Waited");Non-blocking code
This timer waits 100 milliseconds. The next line runs at once.
setTimeout(() => {
console.log("Done");
}, 100);
console.log("Free to continue");Example
console.log("Start");
setTimeout(() => {
console.log("Timer done");
}, 100);
console.log("End");Key points
- Blocking code makes Node wait before it runs the next line.
- A long loop is blocking code, because Node stays inside it.
- Non-blocking code starts work and moves on at once.
- A timer is non-blocking, because Node moves on while it waits.
- Non-blocking code uses a callback to report when its work finishes.
- Blocking code slows a program, so keep slow work non-blocking.
In this example, the first print shows Start at once. The timer starts and waits 100 milliseconds. The next print shows End while the timer still waits. The timer callback then prints Timer done last.
Note
A short loop is still blocking, but it finishes too fast to notice.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which code is non-blocking?