Callback Functions and Event Listeners
A callback is a function you hand to another function to be called later. Event listeners are callbacks that fire when users interact with the page.
Callbacks let do async work despite being single-threaded. The browser handles timers and events; callbacks run when the work is done and the stack is clear.
EXERCISE
1What Is a Callback Function?
A callback is a function you hand to another function, saying: "call this when you are ready." It is the foundation of asynchronous JavaScript.
A callback is a function you hand to another function so that it can be called later. "Later" might mean immediately, at the end of some work, or in two seconds when a timer expires. The receiving function decides.
function processOrder(orderId, onComplete) {
console.log("Processing order #" + orderId);
onComplete();
}
processOrder(42, function () {
console.log("Order complete, send the email");
});
processOrder knows how to process an order and nothing about email. What happens afterwards arrives as an argument, so the same function can notify a user, write a log, or update a screen without being changed.
That example is synchronous: the callback runs before processOrder returns. The more interesting case is when it does not.
console.log("Start");
setTimeout(function () {
console.log("Timer done");
}, 2000);
console.log("End");
The output is Start, End, then Timer done two seconds later. JavaScript did not pause at setTimeout. It handed the function to the browser's timer, moved straight to the next line, and finished everything else first.
This is the whole mechanism behind asynchronous JavaScript in a single thread. The engine does not wait. It delegates the waiting to something that can wait, and supplies a function to be run when that thing is finished.
The consequence is that you cannot return a value from asynchronous work:
function getData() {
let result;
setTimeout(function () {
result = "loaded";
}, 1000);
return result;
}
console.log(getData()); // undefined
return result runs immediately, a full second before the assignment. This is one of the most common mistakes people make when they first meet async code, and no amount of rearranging the function fixes it.
The value has to be delivered the same way the work was: through a callback.
function getData(onReady) {
setTimeout(function () {
onReady("loaded");
}, 1000);
}
getData(function (value) {
console.log(value); // "loaded", one second later
});
Nothing is returned. The result is handed forward instead, at the moment it exists.
EXERCISE
2Event Listeners: Callbacks That Wait for Users
Event listeners are callbacks that fire when a user does something: clicks a button, types in a field, scrolls the page. They sit and wait until the event happens.
An event listener is a callback with no fixed schedule. setTimeout fires once at a known time; a listener waits for something a person does, fires, and then keeps waiting.
document.getElementById("save").addEventListener("click", function () {
console.log("Saved");
});
The function does not run when this line executes. It is registered and left in place, and the browser calls it on every click for as long as the listener remains attached.
Because listeners are callbacks, everything from the closures unit applies to them:
function setupCounter() {
let count = 0;
document.getElementById("save").addEventListener("click", function () {
count += 1;
console.log("Clicked " + count + " times");
});
}
setupCounter();
setupCounter returns immediately, but count survives because the handler refers to it. Every click modifies the same variable, and nothing outside the handler can reach it. That is a private counter built from a closure, holding state across events that may be minutes apart.
The same property is what makes listeners a memory hazard:
function showPanel(rows) {
document.getElementById("refresh").addEventListener("click", function () {
console.log(rows.length);
});
}
Each call adds another listener, and each listener holds its own rows. In a page that calls this on every navigation, nothing is ever released and the tab grows heavier the longer it is open.
Removing a listener requires the same function reference you added, which means it needs a name:
function showPanel(rows) {
const button = document.getElementById("refresh");
function onClick() {
console.log(rows.length);
}
button.addEventListener("click", onClick);
return function cleanup() {
button.removeEventListener("click", onClick);
};
}
const cleanup = showPanel(data);
cleanup();
An anonymous function cannot be removed, because there is no way to name the thing you want taken off. This is the practical reason to give handlers names even when they are used once.
Pro Tip:
removeEventListenercompares by identity, not by shape. Passing an identical-looking function removes nothing at all, and does so silently, which is why the listener you thought you cleaned up is often still attached.
EXERCISE
3Never Block the Main Thread
Since JavaScript runs on a single thread, any long-running code blocks everything else: animations freeze, clicks stop responding, and the page feels dead.
There is one thread. Everything competes for it: your code, click handling, scrolling, animation, layout. While a function is running, none of the rest can happen.
console.log("before");
const end = Date.now() + 3000;
while (Date.now() < end) {
// busy for three seconds
}
console.log("after");
For those three seconds the page is frozen. Clicks are not lost, they are queued, and they all arrive at once when the loop ends. Animations stop mid-frame. In a browser this is the difference between an application and something people close.
The word "blocking" means exactly this: holding the thread so nothing else can use it.
Asynchronous work does not block, because the waiting happens elsewhere:
console.log("request sent");
setTimeout(function () {
console.log("response handled");
}, 3000);
console.log("page still responsive");
Three seconds pass here too, but the thread is free the whole time. The browser holds the timer; JavaScript carries on. Clicks are handled, animations run, and the callback joins the queue when its moment comes.
The trap is that some slow work is not I/O and cannot be delegated:
function sumTo(n) {
let total = 0;
for (let i = 0; i < n; i++) {
total += i;
}
return total;
}
console.log(sumTo(1000000000));
There is no browser to hand this to. It is computation, and computation runs on the thread. Wrapping it in setTimeout does not help, because the callback still executes on the same single thread; it only moves the freeze slightly later.
For genuinely heavy computation the answer is a Web Worker, which runs on a separate thread and communicates by messages. For everything else the answer is simply to use the asynchronous API rather than waiting on the result.
Pro Tip: A useful test: does this operation wait for something outside JavaScript, or does it think? Waiting can be delegated and should be asynchronous. Thinking cannot, and if it takes long enough to notice it belongs in a worker.
