A callback function in JavaScript is a function that is called after another function has completed execution to perform additional operations. Its usage steps include: defining a callback function containing the code to be executed. Pass the callback function to the main function as a parameter. After the main function performs a specific task, the callback function is called.
Callback function in JavaScript
What is a callback function?
The callback function is a function that is called after the execution of another function (the main function) is completed. Its function is to allow the main function to perform additional operations after performing a specific task.
Usage of callback function
The steps to use callback function are as follows:
Example
The following example shows how to use callback functions in JavaScript:
<code class="js">function printMessage(message) { console.log(message); } function delayPrint(message, delay) { setTimeout(() => { printMessage(message); }, delay); } delayPrint("Hello World!", 2000);</code>
In this example:
printMessage
is a callback function used to print messages. delayPrint
is a main function that calls setTimeout
to delay the execution of printMessage
. delayPrint
completes its task (after 2 seconds), it calls the callback function printMessage
. Advantages
The advantages of using callback functions include:
The above is the detailed content of How to use callback function in js. For more information, please follow other related articles on the PHP Chinese website!