Synchronous JavaScript
In synchronous programming, operations are performed one after the other, in sequence. So, basically each line of code waits for the previous one to finish before proceeding to the next. This means that the program executes in a predictable, linear order, with each task being completed before the next one starts.
Example: In this example, we have shown the synchronous nature of JavaScript.
console.log("Hi");
console.log("Geek");
console.log("How are you?");
Output
Hi
Geek
How are you?
Asynchronous JavaScript
"I will finish later!"
Functions running in parallel with other functions are called asynchronous
A good example is JavaScript setTimeout()
Asynchronous JavaScript
The examples used in the previous chapter, was very simplified.
The purpose of the examples was to demonstrate the syntax of callback functions:
Example
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.
Top comments (0)