Scheduling Events

When we want to make a piece of code run in the future in JavaScript, we put it in a callback. A callback is just an ordinary function, except that it’s passed to a function like setTimeout or bound as a property like document.onready. When a callback runs, we say that an event (e.g., the timeout elapsing or the document becoming ready) has fired.

Of course, the devil is in the details, even for something as seemingly simple as setTimeout. A common description of setTimeout goes something like this:

Given a callback and a delay of n milliseconds, setTimeout runs that callback n milliseconds later.

But as we’ll see in this section, and throughout this chapter, that description is seriously flawed. In most cases, it’s ...

Get Async JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.