What Are JavaScript Callback Functions?
In this article, we will explore callback functions in JavaScript, which allow us to perform asynchronous operations, and understand where they are used. We will simulate a real-life scenario to grasp their concept.
What is a Callback Function?
Callback functions are structures used to pass one function as an argument to another function. They are employed when we want something else to happen after an operation is completed.
JavaScript operates synchronously and is single-threaded, but due to its nature and applications, it frequently encounters asynchronous tasks. We often want to continue with other tasks without waiting for lengthy operations to finish, avoiding getting blocked. However, if there is a dependent operation on the output of a time-consuming task in the subsequent lines, the code won’t work as intended.
So, how will other tasks dependent on these time-consuming operations know when they are completed, whether they succeeded, or encountered errors? This is where callbacks come into play.
As you can see, asynchronous JavaScript functions like setTimeout, setInterval, fetch, etc., always require callback functions. We have just discussed the reasons behind this.
In essence, callback functions are functions passed as parameters to another function, called within that function, and they assist in the consistent operation of interdependent asynchronous tasks. As mentioned earlier, asynchronous JavaScript functions like setTimeout, setInterval, fetch, etc., always require callback functions.
Scenario
In our web application, we have a file upload process. Since this operation takes a considerable amount of time, instead of presenting the user with a frozen screen, we want to provide feedback during the upload, showing what percentage of the task is completed based on the uploaded file size.
Step 1:
Let’s create an upload function that accepts a callback. This upload function will have a current value representing the instantaneous progress and a total value indicating the entire duration of the task, similar to the uploaded file size.
Think of the upload function as having an instantaneous value that changes as the upload progresses, and a total value representing the file size.
function upload(callback) {
var current = 0;
var total = 5;
var interval = setInterval(() => {
current += 1;
callback(current, total);
if (current == total) clearInterval(interval);
}, 1000);
}
Here, we have a task with an initial value of 0 and a target value of 5. This task increases by 1 unit every second, triggering the callback with two arguments: current progress and total value.
Step 2:
Let’s invoke the upload function with a callback argument.
upload((current, total) => {
progress.innerHTML = current / total * 100 + "%";
});
Step 3:
Display on the screen.
Loading..
<div id="progress"></div>
Conclusion
We have learned how to pass callback functions to higher-order functions, which are functions that take other functions as arguments, and how the main function operates. This knowledge enables us to perform asynchronous tasks in JavaScript, allowing us to execute multiple operations simultaneously and providing a seamless user experience, despite JavaScript being single-threaded. You can access the application code here.
For further reading on callback functions, you can check out this article.
For a real file upload process, you can use Ajax upload with a progress event and pass a callback that takes an event argument. You can control the upload moment using event.loaded
and event.total
. For detailed information, refer to the article mentioned above.