Chapter 4 · Real programs

Waiting: the event loop

You are reading the whole lesson on one page. Back to one step at a time

Step 1 of 22 · Concept

Programs that wait

By the end of this lesson your programs wait without stopping. You will:

  • run a function later, with a timer,
  • wait for a value with await while other work goes on,
  • read and write files that outlast the program.
function later() {
  console.log("later");
}
console.log("start");
setTimeout(later, 100);
console.log("end");
setTimeout(() => console.log("300 ms"), 300);
setTimeout(() => console.log("100 ms"), 100);
setTimeout(() => console.log("100 ms, second"), 100);
setTimeout(() => console.log("0 ms"), 0);
console.log("main done");
const start = Date.now();
setTimeout(() => {
  console.log("timer: late?", Date.now() - start >= 200);
}, 10);
while (Date.now() - start < 200) {
  // busy: nothing else can run
}
console.log("loop done");
let n = 0;
const id = setInterval(() => {
  n++;
  console.log("tick", n);
  if (n === 3) {
    clearInterval(id);
  }
}, 50);
console.log("interval set");
let n = 3;
// every 50 ms: log n and take 1 from it;
// when n is 0, log Go! and clear the interval
function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
async function brew(drink) {
  console.log("brewing", drink);
  await wait(100);
  console.log(drink, "ready");
}
brew("tea");
console.log("meanwhile");
setTimeout(() => console.log("timer, 0 ms"), 0);
async function step() {
  await null;
  console.log("after await");
}
step();
console.log("script done");
async function getPrice() {
  return 5;
}
const price = getPrice();
console.log(price + 1);
function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
async function task(name, ms) {
  await wait(ms);
  console.log(name, "done");
  return name;
}
const slow = task("slow", 200);
const fast = task("fast", 50);
const results = await Promise.all([slow, fast]);
console.log(results);
function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
// 1. make(name, ms)
// 2. start tea (100 ms) and toast (50 ms)
// 3. await both, then log Breakfast: tea, toast
import { readFile, writeFile } from "node:fs/promises";

const tasks = ["Buy milk", "Write report"];
await writeFile("tasks.json", JSON.stringify(tasks));
const text = await readFile("tasks.json", "utf8");
const again = JSON.parse(text);
console.log(again.length, "tasks:", again.join(", "));
try {
  await readFile("nope.json", "utf8");
} catch (e) {
  console.log(e.code);
}
async function load() {
  throw new Error("no file");
}
load();
console.log("after the call");
import { readFile, writeFile } from "node:fs/promises";

// 1. save [90, 75] as JSON in scores.json
// 2. read them back, add 95, save again
// 3. read once more: log the best and the count
function ring() {
  console.log("ring");
}
const alarm = setTimeout(ring, 100);
// snooze: cancel alarm, log snoozed,
// and set a new alarm for 200 ms
Terminal
Step 1 of 14Later means after the end

Keyboard shortcuts

The step

ContinueEnter
Previous / next stepAlt+[ · Alt+]
Move along the steps bar← → Home End, then Enter
From a quiz's title to its answers↓
Skip to the stepTab, then Enter (first on the page)
Course outlineAlt+O
These shortcuts?

The workspace

Run the stepCtrl+Enter (⌘↵ on a Mac)
Lesson → editor → consoleF6 (Shift+F6 back)
Output ↔ TerminalCtrl+`
Focus the editorCtrl+. (⌘. on a Mac)
Hide or show the lessonAlt+L
Restore, close a messageEsc (outside the editor and the terminal)

The editor

Leave the editorF6 (Shift+F6 back); or Ctrl+M (⌃⇧M on a Mac), then Tab moves the focus (not in the vim mode)
Open a file by nameCtrl+P (⌘P on a Mac)
All commandsCtrl+Shift+P (⌘⇧P on a Mac) or F1
Go to a lineCtrl+G (⌃G on a Mac)
Show or hide the filesCtrl+B (⌘B on a Mac)
Previous / next file tabCtrl+Shift+[ · Ctrl+Shift+] (⌘⇧[ · ⌘⇧] on a Mac)
The file tabs← → Home End on a tab; Delete closes it
Save the files nowCtrl+S (⌘S on a Mac)
Go to a symbol in the fileCtrl+Shift+O (⌘⇧O on a Mac)
Go to the definitionF12
Format the fileCtrl+Shift+F (⌘⇧F on a Mac), or Shift+Alt+F
Go back / forward after a jumpAlt+← · Alt+→ (⌃- · ⌃⇧- on a Mac)