In this video, you started an egg timer for Sam’s recipe box and saw that setTimeout() doesn’t pause your code. The video’s Soft-boiled eggs recipe is a starter the box gains later in the course, so your box doesn’t show it yet.
Key Points
setTimeout()takes a callback and a delay in milliseconds. It calls the callback once the delay is up and JavaScript has nothing else running. Busy code or a tab in the background can make that later than the delay. A two-second toy timer uses2000. The callback works like the one you pass toaddEventListener(): you hand it over, and the browser calls it later.- It doesn’t pause anything. If you read it as a sleep command, you’d expect the code after it to wait too. Instead,
setTimeout()hands the browser your callback and returns at once, and only the callback waits. - JavaScript on a page does one thing at a time. A loop that waits by checking the clock freezes the page, so clicks and typing do nothing until it ends. A timer that paused your code would freeze Sam’s page for all six minutes.
- Now and later: the lines around
setTimeout()run now, and the callback runs later, when the time’s up and JavaScript has nothing else running. - Timers aren’t the only slow things. Loading a file the app ships with, or reading a file the user picks, works the same way. Your code starts it now, and the result arrives later without freezing the page.
The Code
Open your copy of Sam’s recipe box from the last course, or the one in the course’s Sample Code download, folder 01-why-async/recipes-start. Type this into its Console as one entry, pressing Shift+Enter between the lines:
console.log("Eggs on");
setTimeout(() => console.log("Eggs are ready"), 2000);
console.log("Back to the recipe box");
Eggs on and Back to the recipe box appear together, straight away, followed by a muted undefined. That’s the Console’s echo of what the last console.log() returned. Your code didn’t log it. Eggs are ready appears about two seconds later:
Eggs on
Back to the recipe box
Eggs are ready
| Now | Later |
|---|---|
console.log("Eggs on"); |
console.log("Eggs are ready"), after 2 s |
setTimeout(...), which only schedules |
|
console.log("Back to the recipe box"); |
The hand-written wait from the video is a demo, not code to keep:
const doneAt = Date.now() + 3000;
while (Date.now() < doneAt) {}
console.log("Done waiting");
While it runs, clicking the Name field and typing shows nothing. After three seconds, Done waiting appears, and only then do the letters land in the field.
Next, in Follow the Scope Chain, you’ll see how JavaScript finds the names a function uses. That’s the first step to a timer’s callback knowing which pan it’s for.