Why setTimeout’s Callback Runs After All Code: Queues, IDs, and Closures Explained
This article explains how setTimeout works in JavaScript, covering its two parameters, the unique timer ID, the event‑queue execution after the call stack clears, and how closures can be used to preserve loop indices for correct output.
Question
The problem shows a setTimeout example where a mysterious number 7 appears, prompting the question: what does this number represent?
Answer
When learning setTimeout, we quickly notice it takes two arguments: a function to execute and a delay in milliseconds.
Each call to setTimeout returns a unique identifier; the number 7 in the screenshot is such an ID. Developers often store this ID to later cancel the timer with clearTimeout.
Beyond the ID, an important question is when the callback defined in setTimeout actually runs. In browsers, all callbacks created by setTimeout are placed into a single queue and are executed only after the call stack becomes empty.
This means that even if the delay is set to 0, the callback will wait until all synchronous code finishes. The order in which callbacks enter the queue is determined by their specified delays.
To illustrate the concept, consider a loop that creates several setTimeout calls. Because the loop finishes before any callback runs, the loop variable i will have its final value when the callbacks execute, leading to unexpected results (e.g., all callbacks logging 6 when the loop runs from 0 to 5).
To obtain the expected sequential output, we must capture the current value of i for each iteration. This is achieved by using a closure: wrap the setTimeout call in an immediately‑invoked function expression (IIFE) that receives the current i as an argument and stores it in its own scope.
Alternatively, the closure can be created directly in the first argument of setTimeout.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Tencent IMWeb Frontend Team
IMWeb Frontend Community gathering frontend development enthusiasts. Follow us for refined live courses by top experts, cutting‑edge technical posts, and to sharpen your frontend skills.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
