Introduction
Callbacks, usually used for asynchronous actions, are functions passed into some other functions as arguments to be executed later (as required by asynchronous actions). Some JavaScript functions that let us schedule asynchronous actions are setTimeout, loadScript, etc. We will be discussing the loadScript function as an example to explain the need for callbacks.
Callbacks provide a sequence control over the code such that users have more control when implementing and executing the functions. The need for repeatedly creating functions for every time similar tasks need to be performed is eliminated.
Examples of callback functions and methods
loadScript() loads scripts and modules in Js when given a script (which will be ‘scr1’ in our case). loadScript() will create a script tag, append it to the page. Loading scripts is an asynchronous action. Hence it will start loading first but will be executed by the browser only when complete, by which the function will already be finished.
function loadScript(scr1)
{
let script = document.createElement('script');
script.scr1 = scr1;
document.head.append(script);
}
The function can be used as loadScript(...). Since the execution will happen after the function finishes, any code below loadScript() will not wait for the script loading to finish. This means that declaring and running new functions below would not be possible
loadScript('/my/script.js');
It would be helpful to find out when the script finally runs to use new variables and functions from the script. Therefore, we will add a callback function as an argument to loadScript(), which will execute when the script will load. To call new functions from the script, we will now write those in the callback itself.
function loadScript(scr1, callback)
{
let script = document.createElement('script');
script.scr1 = scr1;
script.onload = () => callback(script);
document.head.append(script);
}
Adding a new function in the callback itself:
loadScript('/my/script.js', function()
{
newFunction();
...
});
When to actually use callbacks?
Callbacks are usually preferred to be used in asynchronous actions where functions do not have to wait for one task to be over before proceeding to the next one. One such asynchronous Javascript function where callbacks can be used is setTimeout(), among many others.




