Loading Please Wait...
Functions running in parallel with other functions are called asynchronous. A good example is JavaScript setTimeout().
The examples used in the previous chapter, was very simplified.
The purpose of the examples was to demonstrate the syntax of callback functions:
function myDisplayer(something) {
document.getElementById("demo").innerHTML = something;
}
function myCalculator(num1, num2, myCallback) {
let sum = num1 + num2;
myCallback(sum);
}
myCalculator(5, 5, myDisplayer);
In the example above, myDisplayer is the name of a function.
It is passed to myCalculator() as an argument.
In the real world, callbacks are most often used with asynchronous functions.
When using the JavaScript function setTimeout(), you can specify a callback function to be executed on time-out:
setTimeout(myFunction, 3000);
function myFunction() {
document.getElementById("demo").innerHTML = "I love You !!";
}
In the example above, myFunction is used as a callback.
myFunction is passed to setTimeout() as an argument.
3000 is the number of milliseconds before time-out, so myFunction() will be called after 3 seconds.
Instead of passing the name of a function as an argument to another function, you can always pass a whole function instead:
setTimeout(function(){
alert('Hello');
}, 3000);
When using the JavaScript function setInterval(), you can specify a callback function to be executed for each interval:
setInterval(myFunction, 1000);
function myFunction() {
let d = new Date();
document.getElementById("demo").innerHTML=
d.getHours() + ":" +
d.getMinutes() + ":" +
d.getSeconds();
}
In the example above, myFunction is used as a callback.
myFunction is passed to setInterval() as an argument.
1000 is the number of milliseconds between intervals, so myFunction() will be called every second.
With asynchronous programming, JavaScript programs can start long-running tasks, and continue running other tasks in paralell.
But, asynchronus programmes are difficult to write and difficult to debug.
Because of this, most modern asynchronous JavaScript methods don't use callbacks. Instead, in JavaScript, asynchronous programming is solved using Promises instead.
How you feel about this blog:
Share this blog on:
If you find any error in the turtorials, or want to share your suggestion/feedback, feel free to send us email at: info@lynxsia.com
Contact UsWe are concern with various development process like website design & development, E-commerce development, Software development, Application development, SMS & Bulk SMS Provider, PWA Development, and many more..
Copyright ©
, Lynxsia IT Solutions, All rights reserved