What Are Callbacks?
In JavaScript, a callback is a function that is passed as an argument to another function and is executed after the completion of that function. Callbacks enable you to work with asynchronous code, such as handling user input, making API requests, or reading files, without blocking the main thread. This non-blocking behavior is vital for creating responsive and efficient web applications.
Let's see the Example of the callback function
const datas = [
{
name: "Vineet",
profession: "Software Engineer",
},
{
name: "Vikash",
profession: "Consultant",
},
];
function getDatas() {
setTimeout(() => {
let output = "";
datas.forEach((data, index) => {
output += `<li> ${data.name} </li>`;
});
document.body.innerHTML = output;
}, 1000);
}
function setDatas(newData,callback){
setTimeout(() =>{
datas.push(newData);
callback();
},2000)
}
setDatas({name: "Akash", profession: "Software Tester"},getDatas);
//Ouput of the Code
* Vineet
* Vikash
* Akash
Explanation of the above code
The datas array holds two objects with name and profession properties, representing individuals' information.
The getDatas function is defined. Inside this function:
It uses
setTimeout
to introduce a delay of 1000 milliseconds (1 second).Within the setTimeout callback, it iterates over the datas array using forEach and generates an HTML list containing each person's name.
Finally, it sets the generated HTML as the content of the document body element, effectively updating the webpage with the list of names.
The setDatas function is defined, which takes two arguments:
newData: An object representing a new person's information.
callback: A callback function to be executed after adding the new data to the datas array.
Inside the setDatas function:
It uses setTimeout to introduce a delay of 2000 milliseconds (2 seconds).
The setTimeout callback adds the newData object to the datas array using the push method.
After adding the new data, it calls the provided callback function.
Finally, the setDatas function is called with a new data object, and the getDatas function as a callback. This means that when the new data is added to the datas array, the getDatas function will be executed after a 2-second delay. This demonstrates an asynchronous operation where the getDatas function displays the updated data on the webpage after the new data is added.