- Synchronous code runs one line at a time, waiting for each to finish. Asynchronous code starts slow tasks and carries on, handling the results later.
setTimeout(fn, ms)runs a function once after a delay.setInterval(fn, ms)runs it repeatedly. Cancel them withclearTimeoutandclearInterval.- Asynchronous callbacks always run after the current code finishes, even with a delay of 0.
- Nesting callbacks leads to the Pyramid of Doom.
- A Promise represents a future value. It's pending, then either fulfilled (with a value) or rejected (with an error).
- Use promises with
.then(),.catch()and.finally(). Chains of.then()avoid nesting. - Create promises with
new Promise((resolve, reject) => { ... }). asyncfunctions always return a promise. Inside them,awaitpauses until a promise settles. Usetry...catchfor errors.Promise.all([...])runs independent tasks in parallel and waits for all of them.fetch(url)requests data from the internet. Checkresponse.ok, then useawait response.json().- The event loop runs queued callbacks whenever the call stack is empty. Promise callbacks (microtasks) go before timer callbacks.
Reading is step one
CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.