Callbacks, setTimeout, & the Event Loop

Learn how JavaScript is both single-threaded and asynchronous. We'll go over how the event loop creates an event-based system that is at the core of how modern websites work. We'll see how to respond to events efficiently and how to write asynchronous code.

What Callbacks Do

Callbacks are absolutely vital to asynchronous programming. The only way for us to tell JavaScript to do something in the future is to provide a callback that will be invoked later.

JavaScript allows us to attach a callback to a particular event. We can tell JavaScript that when some event happens, we want to run some function. That’s the gist of the whole concept.

The event can be anything. In a browser, it can be a button click from a user. On a file system, it can be a file read operation. We can attach handlers to these events, saying that every time this event happens, we want something else to happen.

For example, when a user clicks a button, perhaps we want to load more content or open a pop-up. When a file read operation occurs, perhaps we want to log the event for security and auditing purposes.

To set up an event listener on a button, we pass in a callback to a function such as jQuery. That function binds our callback to the button. When the button is clicked, our callback is called and whatever changes need to happen to the page occur through it.

How to Use them

DOM

If you’ve ever used jQuery you’ve seen that it’s entirely based on callbacks.

Get hands-on with 1200+ tech skills courses.