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:

Important Concepts:

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 read

3. Callback with setTimeout()

Example Code 2:

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 display

Example Code 3:

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 display

Example Code 4:

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 display

Example Code 5:

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 display

4. Repeated Execution Using setInterval()

Example Code 6:

Key Points:

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

6. Modern Alternatives

Due to complexity in managing callbacks, modern JavaScript uses:

These approaches provide better readability and easier error handling compared to traditional callbacks.