Lesson 2 · Unit 01
The event loop
One thread, a queue of callbacks, no interruptions
What you practise
- One thread and a queue of callbacks, run-to-completion, timers and why
setTimeout(0)(orcall_soon) runs later, blocking the loop freezes everything
Try a question from this lesson
Pick one
The middle of this program does not print B itself: it puts that job in a queue for later. In what order do the letters appear?
queue = []
def later(job):
queue.append(job)
print("A")
later(lambda: print("B"))
print("C")
while queue: # the event loop
job = queue.pop(0)
job()console.log("A");
setTimeout(() => console.log("B"), 0);
console.log("C");console.log("A");
setTimeout(() => console.log("B"), 0);
console.log("C");Correct answer
A C B
Why
Queueing a job does not run it. The queue is only looked at once the code that is running has finished, so C prints before B, every time.
Python noteThis is a toy event loop in ten lines: a list of jobs and a while that runs them. asyncio is the real one, with timers and I/O added.
JavaScript notesetTimeout(fn, 0) means "queue fn as soon as you can", not "run it now". The JavaScript engine has the loop built in.
TypeScript notesetTimeout takes a function and a delay in milliseconds, and returns a handle you can pass to clearTimeout.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
One thread, one queue
An event loop is one thread running this forever: take the next callback from the queue, run it to the end, repeat.
Timers and finished I/O do not interrupt anything. They add a callback to the queue, and it waits its turn.
So code you queue runs later, after the code that queued it.
import asyncio
async def main():
loop = asyncio.get_running_loop()
loop.call_soon(print, "later")
print("running")
await asyncio.sleep(0) # let it run
asyncio.run(main()) # starts the loopsetTimeout(() => console.log("later"), 0);
console.log("running");setTimeout(() => console.log("later"), 0);
console.log("running");Python noteasyncio.run(main()) starts the loop with main as its first job. call_soon(f, x) queues the call f(x). await asyncio.sleep(0) pauses main so the loop can work through its queue.
Concept
Never block the loop
While one callback runs, nothing else can: no timers, no clicks, no other requests. There is only one thread.
A callback that computes for 2 seconds, or puts the whole thread to sleep, freezes everything for 2 seconds.
Keep callbacks short. Hand long waits to the loop instead of sitting in them.
9 more exercises in the app
- 3× type the answer
- 1× true or false
- 3× multiple choice
- 1× fill the blanks
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.