Callbacks
Learn about JavaScript callbacks and their usage with the setTimeout function, which registers a function to execute after an asynchronous event.
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:
// This function takes a callback function as a parameterfunction delayedResponseWithCallback(callback: () => void) {function executeAfterTimeout() {console.log(`5. executeAfterTimeout()`);// This line calls the callback function passed in as a parametercallback();}console.log(`2. calling setTimeout`)// This line schedules the executeAfterTimeout function to be called after 1000 mssetTimeout(executeAfterTimeout, 1000);console.log(`3. after calling setTimeout`)}
-
We have a function named
delayedResponseWithCallback
that has a single parameter namedcallback
, which is a function with no arguments that returnsvoid
. -
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 namedcallback
.
Note: Each console log in the above code snippet starts with a number, which ...