In this article you will know that What is a callback function in JavaScript?
Using a callback function is with the ‘setTimeout()’ function. The ‘setTimeout()’ function takes two arguments: a function to execute, and a time delay in milliseconds. The function that is passed as the first argument is executed after the specified delay has passed.
function greeting(name) { console.log(`Hello, ${name}!`); } setTimeout(function() { greeting('John'); }, 1000);
In the above example, the ‘setTimeout()’ function is used to delay the execution of the ‘greeting()’ function for 1000 milliseconds (1 second). When the timeout is complete, the callback function is executed, and it calls the ‘greeting()’ function with the argument “John”.
Output:
(after 1 second) Hello, John!
This is a simple example of a callback function in JavaScript, but callback functions can be used for many different purposes, such as event handling, asynchronous data processing, and more.