Level: Intermediate | Player: 13_Higher-order functions
Learning Objectives
- Understand the difference between synchronous and asynchronous.
- Use
setTimeout,setInterval,clearTimeout, andclearInterval. - Understand the concept of the event loop as a big picture.
- I recognize why callback hell is a problem and feel the need for the next section (Promise).
- Prevent resource leaks by managing timer IDs.
1. Synchronous vs. asynchronous
Synchronous code is executed line by line, with one task completing before moving on to the next. Asynchronous code schedules “something to run later” and immediately moves on to the next code.
console.log("A");
setTimeout(() => console.log("B"), 0);
console.log("C");
//Output: A, C, B
Even setTimeout(fn, 0) runs after all synchronous code has finished.
2. setTimeout and clearTimeout
setTimeout(fn, ms) executes the callback once after the specified number of milliseconds. The return value is the timer ID, and can be canceled with clearTimeout(id).
const id = setTimeout(() => console.log("not running"), 1000);
clearTimeout(id);
ms is "minimum latency", not "exact time". If the main thread is busy, it will run slower.
3. setInterval and clearInterval
setInterval(fn, ms) repeats callbacks at regular intervals. It must be disposed of as clearInterval when it is no longer needed.
let n = 0;
const id = setInterval(() => {
n += 1;
if (n >= 3) clearInterval(id);
console.log(n);
}, 500);
4. Event loop (big picture)
JavaScript is single-threaded, but the Timer/Network API provided by the host environment (Browser/Node) operates separately. Callbacks are queued and executed one by one when the call stack is empty. More details are covered in Lesson 16 and beyond.
5. Callback Hell
If asynchronous operations are required in succession, callbacks are placed within callbacks, deepening the indentation.
step1((a) => {
step2(a, (b) => {
step3(b, (c) => {
console.log(c);
});
});
});
To solve this problem, learn Promise in Unit 15 and async/await in Unit 16.
Core example
| file | Contents covered |
|---|---|
| 01_settimeout.js | setTimeout/clearTimeout default |
| 02_setinterval.js | Repeat with setInterval + termination condition |
| 03_event_loop.js | Observe synchronous/asynchronous execution order |
| 04_callback_hell.js | Demonstrating the problem of callback nesting |
⚠️ Common Mistakes
- Immediately call the function (in parentheses) like
setTimeout(fn(), 1000)and pass the result. - Leak occurred because
setIntervalwas created andclearIntervalwas forgotten. - Expect
setTimeout(fn, 0)to run immediately. - Attempting to catch an error thrown within an asynchronous callback with an external try/catch.
- Using
thisinside the callback without knowing that it is different from the outside (resolved with arrow function).
❓ Frequently Asked Questions (FAQ)
Q1. What is the difference between setTimeout 0ms and immediate execution? A. 0ms also goes through the queue once, so it is executed after all current synchronous code is finished.
Q2. Difference between setInterval and recursive setTimeout? A. setInterval tries to maintain the interval regardless of the callback execution time, and recursive setTimeout sets the next timer after the callback ends.
Q3. Are the timers in the browser and Node the same? A. The API signature is the same, but details such as minimum delay time and priority queue are different.