Callback Function: A callback is any executable code that is passed as an argument to another code, which is expected to call back (execute) the argument at a given time.
Why do we need Callbacks?
JavaScript runs code from top to bottom.
there are some cases in that code must run after something else happens and
also not using a top-down approach.
## Callbacks are used to make sure that a function is not going to execute
before a task is completed
will execute right after the task has been completed. It helps us develop asynchronous JavaScript code and keeps us safe from future errors.
How to create a Callback:-There is a built-in method called “setTimeout”, which calls a function after a given period of time. So here, the myMessage function is being called after 5 seconds. (1 second = 1000 milliseconds). In other words, the myMessage function is being called after something happened (after 5 seconds passed for this example), but not before. So, the myMessage function is an example of a callback function.
Here source code :
function addition(x, y , callback){
setTimeout(() => {
document.write(`The sum of ${x} and ${y} is ${x+y}.`);
callback();
}, 5000); }
// display() function is called just after the ending of addition() function
function display(){
document.write('Numbers added!');
}
// Calling addition() function
addition(5,5,display);
Here is all code:
console.log("This is tutorial 37");
// Pretend that this response is coming from the server
const students = [
{name: "harry", subject: "JavaScript"},
{name: "Rohan", subject: "Machine Learning"}
]
function enrollStudent(student, callback){
setTimeout(function() {
students.push(student);
console.log("Student has been enrolled");
callback();
}, 1000);
}
function getStudents(){
setTimeout(function() {
let str = "";
students.forEach(function(student){
str += `<li> ${student.name}</li>`
});
document.getElementById('students').innerHTML = str;
console.log("Students have been fetched");
}, 5000);
}
let newStudent = {name:"Sunny", subject:"Python"}
enrollStudent(newStudent, getStudents);
// getStudents();
##Note: Callback functions are both synchronous and asynchronous.
Comments
Post a Comment