The weather station dashboard asks the Ridge station for a reading and, while it waits for the reply, replays archived readings to warm up its averages. Your Python prototype did this with a thread timer standing in for the station. In the JavaScript port, the reply never shows up while the replay runs, even when it’s due straight away.
In this lesson, you’ll see why a due timer can’t break into running code and how to wait for a result so the dashboard gets it.
Wait for a Timer in a Loop
The Python prototype fakes the Ridge reply with threading.Timer, which calls a function on another thread after a delay. The main thread replays up to 50 million archived readings, with a counter increment standing in for each one’s CPU work, and stops once the event is set:
import threading
ridge_ready = threading.Event()
def handle_ridge_reply():
ridge_ready.set()
print("Ridge reply handled")
timer = threading.Timer(0, handle_ridge_reply)
timer.start()
replayed = 0
while not ridge_ready.is_set() and replayed < 50_000_000:
replayed += 1
timer.join()
print("after waiting:", ridge_ready.is_set())
The loop stops early, and joining the timer keeps the lines in this order:
Ridge reply handled
after waiting: True
In the JavaScript port, setTimeout() takes a callback function to run later and a delay in milliseconds. A reassignable let variable holds the flag. JavaScript’s while puts its condition in parentheses and its body in braces. ! is Python’s not, && is its and, and underscores group digits, as in Python:
let ridgeReady = false;
setTimeout(() => {
ridgeReady = true;
console.log("Ridge reply handled");
}, 0);
let replayed = 0;
while (!ridgeReady && replayed < 50_000_000) {
replayed += 1;
}
console.log("after waiting:", ridgeReady);
The delay is 0, which Node rounds up to 1 millisecond, so the reply is likely due long before the replay ends. Predict what JavaScript prints, then run it:
after waiting: false
Ridge reply handled
The loop replayed all 50 million without seeing the flag change, and the callback ran only after the module’s last line. The output is the same on every run, however fast the loop is.
Draw the Stack and the Queue
Your module runs on one main thread with one call stack, which holds the frames of the currently running code. setTimeout() hands the timer to the host (Node here, or a browser) and returns at once. In a simplified model, a due timer’s callback passes through a task queue, and the event loop takes the next task only when the stack is empty. Node’s real loop runs timers in phases, but no timer callback starts while code is on the stack.
Here’s the port at four moments in that model:
| Moment | Call stack | Host’s timers | Task queue |
|---|---|---|---|
setTimeout() returns |
module code | Ridge timer | empty |
| loop running, timer due | module code | Ridge timer (due) | empty |
| module finished | empty | none | Ridge callback |
| callback runs | Ridge callback | none | empty |
The module’s frame stays on the stack for the whole loop, so the due timer stays with the host. This is run-to-completion: each piece of code runs to the end before the next task starts.
Python’s asyncio follows this rule too. Swap the thread timer for loop.call_later() and keep the coroutine from awaiting until the replay ends:
import asyncio
async def main():
ridge_ready = False
def handle_ridge_reply():
nonlocal ridge_ready
ridge_ready = True
print("Ridge reply handled")
loop = asyncio.get_running_loop()
loop.call_later(0, handle_ridge_reply)
replayed = 0
while not ridge_ready and replayed < 50_000_000:
replayed += 1
print("after waiting:", ridge_ready)
await asyncio.sleep(0)
asyncio.run(main())
The output has the same line order as JavaScript’s, but Python spells the Boolean False:
after waiting: False
Ridge reply handled
The callback can’t run before await asyncio.sleep(0), the first point where main() gives the loop control back. So setTimeout()’s closest Python match is call_later(), not threading.Timer, because both event loops are cooperative. Mind the arguments when porting: loop.call_later(1, handler) becomes setTimeout(handler, 1000).
Hand the Reply to a Callback
Moving the loop into an async function doesn’t let the timer in:
let ridgeReady = false;
setTimeout(() => {
ridgeReady = true;
console.log("Ridge reply handled");
}, 0);
async function replayArchive() {
let replayed = 0;
while (!ridgeReady && replayed < 50_000_000) {
replayed += 1;
}
console.log("replayed:", replayed);
}
replayArchive();
console.log("replayArchive() returned, ready:", ridgeReady);
The function ran its whole loop before the call even returned:
replayed: 50000000
replayArchive() returned, ready: false
Ridge reply handled
Python differs here. Calling an async def function only creates a coroutine. The function’s body waits until you await the coroutine:
import asyncio
async def replay_archive():
print("replay started")
async def main():
replay = replay_archive()
print("replay_archive() returned")
await replay
asyncio.run(main())
The body starts only at the await:
replay_archive() returned
replay started
A JavaScript async function starts running at once on the caller’s stack and continues until its first await. The blocking matches Python: a coroutine with no await holds up asyncio’s loop too.
The fix is to stop polling a flag. Keep the replay, put the code that needs the reply inside the callback, and let the module finish so the stack empties:
function showRidge() {
console.log("Ridge panel updated");
}
setTimeout(() => {
console.log("Ridge reply handled");
showRidge();
}, 0);
let replayed = 0;
while (replayed < 50_000_000) {
replayed += 1;
}
console.log("replayed:", replayed);
The replay finishes, the stack empties, and the reply gets its turn:
replayed: 50000000
Ridge reply handled
Ridge panel updated
The reply still waits for the replay to end because nothing can break into running code. Now the code that needs the reply runs once the stack is free and Node reaches its timers, with no flag to poll.
To wait for a result in JavaScript, hand the follow-up to a callback or await the promise for that result inside an async function, which pauses and leaves the stack until the result arrives. Awaiting an already settled promise, like the one Promise.resolve() returns, isn’t equivalent to awaiting asyncio’s sleep(0): a polling loop that awaits it still starves the timer.
In the next lesson, Promises Run Before the Next Timer, you’ll trace the dashboard’s ordering() check through promises, queueMicrotask(), and a timer to see why it logs start, end, promise, microtask, timer in that order.