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.
We'll cover the following...
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:
-
We have a function named
delayedResponseWithCallbackthat has a single parameter namedcallback, which is a function with no arguments that returnsvoid. -
Within this function, we define another function named
executeAfterTimeouton lines 3–7, which will log a message to the console and then execute the callback function that was passed in as the parameter namedcallback.
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 ...