All 28 lessons ▾
Inside JavaScript · Lesson 14 of 28
Callbacks and Event Listeners
So you give a function to someone else, and they call it later. That's a callback! And now listen carefully, it's how single-threaded JavaScript handles async work.
A new lesson goes up every day at 11 am. Subscribe on YouTube so you don't miss it.
Got a doubt? Ask in the comments under the video.Subscribe
- A callback: a function passed in, to be called later
- Callbacks bring async work to single-threaded JavaScript
- Never block the main thread
- Event listeners are callbacks the browser calls
- With a closure, a listener keeps private state
- Remove listeners you don't need
Part 1What is a callback?
So remember the last episode? Functions are first-class, so you can pass a function into another function. So today, we give that passed function its real name. And once you get this, half of JavaScript suddenly makes sense. Let's start.
So when you pass a function into another function, the function you passed is called a callback. Now why that name? Because you're handing it over and saying, here, call this back when you need it. You give the other function the power to call your function, whenever it decides. So remember this definition, because callbacks are everywhere. Timers, clicks, server requests, all of them.
So here's a picture. You go to a busy restaurant, and there's no table. Do you stand at the counter, staring at the staff? No! You leave your number, and say, call me back when it's ready. Then you're free to go for a walk. Later, your phone rings. Your table is ready! So your number is the callback. The restaurant calls it when the moment comes, and you didn't waste time waiting. That's exactly how JavaScript uses callbacks.
Part 2Callbacks in action
Now let's watch callbacks on the call stack. This program has two of them, and they behave very differently.
1setTimeout(function () {2 console.log("timer");3}, 5000);4 5function x(y) {6 console.log("x");7 y();8}9 10x(function y() {11 console.log("y");12});x y timer
Global is pushed, and phase one stores x. Line one gives a function to setTimeout, with five thousand milliseconds. That function is a callback. setTimeout will call it back, later, and JavaScript moves on. Line ten calls x, and passes it another function, y. x gets a new context, and its parameter y holds that function. Line six prints x. Line seven calls y. So x is calling back the function we gave it. y gets its own context, right on top of x. Line eleven logs y, and the console shows y. y is popped, and x is popped too. The global code is over, so Global goes, and the call stack is empty. Now, five seconds after we started, the timer's callback appears on the stack. It's called anonymous, because it has no name. Line two runs, and finally, timer is printed. And it's gone. So the output is x, y, and then timer.
So remember this. JavaScript is synchronous and single threaded. One call stack, one thing at a time. But callbacks open the door to the asynchronous world. You hand a function over, and it's called back later, when the timer is done, when data arrives, or when a user clicks. So without callbacks, none of that would be possible.
1setTimeout(function () {}, 1000);2 3btn.addEventListener("click", function () {});4 5[1, 2, 3].forEach(function (n) {6 console.log(n);7});And now you've already met callbacks, maybe without noticing. setTimeout takes a callback, and calls it after its timer. addEventListener takes a callback, and calls it on a click. And forEach takes a callback too. It calls it once for every item in the array, right now, one by one. So some callbacks run later, and some run straight away. Now what makes a function a callback is simply this. You pass it in, and someone else calls it. So we'll use this a lot with map, filter, and reduce, later in the course.
Part 3Never block the main thread
Now, an important warning. Every function we just saw ran on that one call stack. It has another name. The main thread. And there's only one of it.
So imagine a click, and a timer, both ready to run their callbacks. But a function called heavyWork is on the call stack, and it takes thirty seconds to finish. What happens? The click waits. The timer waits. Nothing else can run, because the one main thread is busy. The page freezes. This is called blocking the main thread. And what kind of code does this? A loop that runs a billion times. A giant calculation. Code that sits and waits for something, on purpose. While it runs, the browser can't even repaint the screen, so even scrolling stops. So here's the rule. Never block it. Anything that takes time, like waiting for a timer, or a server, should be done asynchronously, with callbacks. So let the waiting happen outside, and come back only when it's ready.
Part 4Event listeners
Now let's meet the callbacks you'll write almost every day, in the browser. Event listeners.
1// <button id="likeBtn">Like</button>2 3var btn = document.getElementById("likeBtn");4 5btn.addEventListener("click", function onClick() {6 console.log("Liked!");7});So here's a button on a page, with the id likeBtn. Line three finds it. And line five calls addEventListener, with two things. Which event, click. And what to do, a function, onClick. And that onClick function? It's a callback! addEventListener keeps it safe. And whenever someone clicks the button, the callback is put on the call stack, and it runs. Liked! Now click ten times, and it runs ten times. You never call onClick yourself. The browser calls it back for you.
1function setupLikes() {2 let likes = 0;3 btn.addEventListener("click", function () {4 likes++;5 console.log("Likes:", likes);6 });7}8setupLikes();Likes: 1 Likes: 2 Likes: 3
Now let's count the likes. We could keep the count in a global variable, but you know the problem. Anyone could change it. So we use a closure instead. Line eight calls setupLikes. Its memory gets likes, zero. Line three attaches the callback, and then setupLikes is done, and popped. Its box is gone. Now the user clicks. The callback runs, and its backpack still has likes. It goes up to one. Click again, two. And again, three. So the count is private, and it survives every single click. Callbacks and closures, working together!
And now you can see this for real. Open DevTools, go to Elements, and select the button. On the side, open the tab called Event Listeners. There's our click listener, and its handler, the callback. Now expand it, and look at its scopes. You'll find Closure, setupLikes, and inside it, likes, with the current count. So that's the backpack, attached to your button, waiting for the next click.
Part 5Listeners and memory
So one last thing, and it's about memory. Event listeners have a hidden cost. Let's see.
So an event listener forms a closure, so it keeps everything in its backpack alive, like likes. And it can't know when the next click will come, so that memory is never freed, as long as the listener is attached. Now imagine a page with hundreds of listeners, for clicks, scrolls, and mouse moves. That's heavy, and the page slows down. So when you don't need a listener anymore, remove it. Then the callback, and its backpack, can finally be garbage collected.
1function onClick() {2 console.log("Liked!");3}4btn.addEventListener("click", onClick);5 6// later, when it's no longer needed7btn.removeEventListener("click", onClick);So here's how. To remove a listener, you must pass the very same function you added. That's why we give it a name, onClick, and pass it to both addEventListener and removeEventListener. Now if you add an anonymous function, you have no way to point at it later, so you can't remove it. A small habit, but it makes a big difference on heavy pages.
1function greet(name, done) {2 console.log("Hi " + name);3 done();4}5 6greet("Asha", function () {7 console.log("Bye");8});9console.log("End");In what order do these lines print?
Show the answer
So greet runs first, and logs Hi Asha. Then it calls done, right away. So Bye prints next. And only then, the last line prints End. Hi Asha, Bye, End. Surprised that Bye came before End? Now here's the lesson. A callback is not automatically async. It runs whenever the other function calls it, and here, that's immediately. Only things like timers and events make it run later.
Where have you used a callback without realizing it?
Answer in the comments under the video.
The video on YouTube, and the lesson as a swipe-through on Instagram.