The answer
Store the return value (a timer ID) and pass it to clearTimeout(id). This cancels the pending timer and the callback will not run.
Store the return value (a timer ID) and pass it to clearTimeout(id). This cancels the pending timer and the callback will not run.
1, 3, 2. The timer callback goes to the macrotask queue and runs after the synchronous code finishes.
Because promise callbacks go to the microtask queue, which the event loop drains completely before touching the macrotask queue where setTimeout callbacks live.
3, 3, 3. var is function-scoped; all callbacks share one i, which is 3 by the time they run. Use let to fix this (logs 0, 1, 2).
Browse all our FAQs or reach out to our support team
Your learning library
Find your next course. Build something great.