...

/

Callbacks

Callbacks

Learn about JavaScript callbacks and their usage with the setTimeout function, which registers a function to execute after an asynchronous event.

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:

// 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 ...