A callback function is a function that is passed to another function as an argument and is called later.
Callback functions are used in JavaScript to handle asynchronous operations and ensure code executes in the correct order after certain tasks (like API calls or timers) complete.
// Define a callback function
function greet(name) {
console.log(`Hello, ${name}!`);
}
// Use the callback after a delay
function delayedGreet(callback) {
setTimeout(() => {
callback("Alice"); // Call the callback after 1 second
}, 1000);
}
// Pass `greet` as a callback
delayedGreet(greet); // Output after 1 sec: "Hello, Alice!"
The greet function is passed as a callback to delayedGreet, ensuring it runs only after the setTimeout completes. This pattern is essential for async tasks like API calls, event handlers, and promises.
0 Comments