DEFINITION:
A callback function is a function that is passed as an argument to another function and is executed after a specific task is completed.
or
A callback is a function that is called later by another function.
function greet(name, ak) {
console.log("Hello " + name);
ak();
}
function sayBye() {
console.log("Goodbye!");
}
greet("Alagu", sayBye);
Explain About code:
- greet() is the main function.
- sayBye() is the callback function.
- After greeting, greet() calls callback().
SetTimeout:
SetTimeout() is a built-in JavaScript function that executes a function after a specified delay.
Basic:
console.log("Start");
setTimeout(function () {
console.log("Hello, JavaScript!");
}, 2000);
console.log("End");
Explanation:
"Start" is printed.
setTimeout() starts a 2-second timer.
"End" is printed immediately.
After 2 seconds, the callback function runs and prints "Hello, JavaScript!".
Named Function:
function welcome() {
console.log("Welcome to the Blog Platform!");
}
setTimeout(welcome, 3000);
Advantages of Callback Functions
Makes code reusable.
Helps execute code after another task finishes.
Essential for asynchronous programming.
Used in events, timers, and API requests.
Improves code organization.
Disadvantages of Callback Functions
Nested callbacks can make code difficult to read.
Too many callbacks can lead to callback hell.
Debugging nested callbacks can be harder.
Top comments (0)