Understanding Callback Functions Through an Image Carousel
After hearing and seeing the term callback functions but not fully understanding what they were, I found clarity by recognizing how they are used in a component I built – an image carousel. (You can view the carousel on CodePen to follow along.)
A callback function is:
A function that is passed into another function, , to be executed later.
Example 1: event listener
rightBtn.addEventListener("click", () => {
idx++;
changeImage();
resetInterval();
});What’s happening:
- addEventListener is a function
- you pass it another function:
() => {
idx++;
changeImage();
resetInterval();
}That function is the callback
This callback function does not run immediately; it runs later, when the user clicks the button.
Example 2: setInterval
setInterval(run, 2000);What’s Happening:
- run is passed into setInterval
- run is also a callback
It runs every 2 seconds, not immediately when JS reads the line
The changeImage Function: Regular Function vs Callback Context
This is a normal function:
function changeImage() {
...
}and this is calling the function:
() => {
idx++;
changeImage();
}This function is a callback. It only runs when the event (like a click) triggers it.
Mental Model
Pass the function → it runs later
Call the function → it runs now
Why Callback Functions Matter
Callback functions are fundamental in frontend development because they allow your code to respond to events and timing.
In this image carousel, callbacks are used for:
- Event handling (button clicks)
- Timers (setInterval)
These are two of the most common patterns in interactive web applications.