Search⌘ K

Callbacks

Explore how callbacks enable asynchronous programming in JavaScript by learning to register and execute functions after time delays or events. Understand the event sequencing in JavaScript runtime through practical examples using setTimeout and multiple callback functions. Gain insight into the mechanics that handle asynchronous calls and their execution order.

Introduction to callbacks

Let’s start by examining callbacks, which is the standard mechanism for registering a function to execute after an asynchronous event has occurred.

Consider the following example:

TypeScript 4.9.5
// This function takes a callback function as a parameter
function delayedResponseWithCallback(callback: () => void) {
function executeAfterTimeout() {
console.log(`5. executeAfterTimeout()`);
// This line calls the callback function passed in as a parameter
callback();
}
console.log(`2. calling setTimeout`)
// This line schedules the executeAfterTimeout function to be called after 1000 ms
setTimeout(executeAfterTimeout, 1000);
console.log(`3. after calling setTimeout`)
}
Callback function
  • We have a function named delayedResponseWithCallback that has a single parameter named callback, which is a function with no arguments that returns void.

  • Within this function, we define another function named executeAfterTimeout on lines 3–7, which will log a message to the console and then execute the callback function that was passed in as the parameter named callback.

Note: Each console log in the above code snippet starts with a number, which shows the order of execution of the statements. We will see logs a little later in the order of 1, 4, and 6.

  • We then log a message to the console to indicate that we are about ...