Author: M Abo Bakar Aslam
Asynchronous
In JavaScript, a callback function is a function that is passed as an argument to another function and is executed after a specific task or event has occurred. This concept is widely used in event-driven and asynchronous programming, such as handling user actions, API calls, and file operations.
Callback functions allow one function to control the execution of another function, making programs more flexible and modular.
1. Asynchronous Nature of Callbacks
Callbacks are especially useful in asynchronous programming, where tasks do not execute sequentially.
Key Idea: A function does not wait for another task to complete; instead, it continues execution, and the callback runs later when the task finishes.
2. File Handling Using Callback (Asynchronous Example)
Example Code 1:
- A file is read asynchronously using a built-in module.
- A callback function handles the result after reading completes.
- The callback receives:
- An error (if any)
- File data (if successful)
Important Concepts:
- Non-blocking execution
- Error handling inside callback
- Execution continues without waiting
const myFs = require('fs');
// Asynchronous file reading
myFs.readFile('example.txt', 'utf8', (error, data) => {
if (error) {
console.error('Error:', error);
} else {
console.log('File content:', data);
}
});
console.log('Reading file...'); // This is executed before the file is read3. Callback with setTimeout()
Example Code 2:
- A function is scheduled to run after a specific delay.
- JavaScript does not pause execution; it continues running other code.
- The callback executes after the delay is completed.
setTimeout(myFunction, 3000) //3000 milisecond = 3 seconds
console.log("String after callback ...1") //1st display
function myFunction() {
console.log("Time out")// last display
}
console.log("String after callback ...2") //2nd displayExample Code 3:
- The callback function is defined directly inside the timing function.
- This avoids separate function declarations.
setTimeout(
function myFunction(){
console.log("Timeout")
},
3000) //3000 milisecond = 3 seconds
console.log("String after callback ...1") //1st display
console.log("String after callback ...2") //2nd displayExample Code 4:
- The callback is written using arrow function syntax.
- Provides a cleaner and more modern approach.
setTimeout(
myFunction =>{
console.log("Timeout")
},
3000) //3000 milisecond = 3 seconds
console.log("String after callback ...1") //1st display
console.log("String after callback ...2") //2nd displayExample Code 5:
- A more concise version of callback function.
- Used when the function contains only a single statement.
setTimeout(myFunction =>{
console.log("Timeout")
},3000) //3000 milisecond = 3 seconds
console.log("String after callback ...1") //1st display
console.log("String after callback ...2") //2nd display4. Repeated Execution Using setInterval()
Example Code 6:
- A callback function is executed repeatedly after a fixed interval.
- Commonly used for timers, clocks, and periodic updates.
Key Points:
- Runs continuously at defined intervals
- Useful for real-time updates
- Requires manual stopping if needed
setInterval(myFunction, 1000) //call after every second (1000 miliseconds)
//definition onf myFunction
function myFunction() {
const d = new Date()
console.log(d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds())
}5. Important Notes About Callbacks
- A callback function runs after another function completes its task.
- It enables asynchronous and event-driven programming.
- JavaScript does not block execution while waiting for callbacks.
- Writing complex callback-based code can become difficult (callback nesting).
6. Modern Alternatives
Due to complexity in managing callbacks, modern JavaScript uses:
- Promises
- Async/Await
These approaches provide better readability and easier error handling compared to traditional callbacks.