JavaScript
CallBack Function
1
What is function ?
A function is a block of code that
performs a certain task when called
In the above program, a string value is
passed as an argument to the greet()
function.
2
What is callback function ?
In JavaScript, you can also pass a
function as an argument to a function.
This function that is passed as an
argument inside of another function is
called a callback function.
3
Benefit of Callback Function
The benefit of using a callback function
is that you can wait for the result of a
previous function call and then execute
another function call.
Benefit of Callback Function
4
In this example, we are going to use the
setTimeout() method to mimic the
program that takes time to execute.
Benefit of Callback Function
5
Here, the greet() function is called after
2000 milliseconds (2 seconds). During
this wait, the sayName('Christo'); is
executed. That is why Hello Christo is
printed before Hello world.
The above code is executed
asynchronously (the second function;
sayName() does not wait for the first
function; greet() to complete).