We know that javascript is single threaded and synchronous language so, how is it possible to make asynchronous calls in javascript?
Before we get into details let's clarify some definitions:
Single Threaded: One command at a time.
Synchronous: One at a time in order.
Asynchronous means, more than one at a time. Not in javascript but in some other programming languages like GO, with goroutine, you can execute a function which executes another function and another function which all of them executes at the same time but, javascript is synchronous and it executes code, "one line at a time, in order".
In javascript we have click events or fetch api where you can define a callback function which will execute right after a certain event.
Here is the thing: Even though javascript is synchronous and single threaded, browsers are not. Browsers are not just javascript interpreters. They have rendering engine, networking component and many more. Javascript engine itself is synchronous but for example when we add an event listener to a button other parts of the browser are looking for, if the condition to fire that event is fulfilled.
Let's take a look at this example:
function waitThreeSeconds() {
var ms = 3000 + new Date().getTime();
while(new Date() < ms) {}
//1st
console.log('I am side effect of this function');
}
function clickHandler() {
//3rd
console.log('click event!');
}
document.addEventListener('click', clickHandler);
waitThreeSeconds();
//2nd
console.log('interpreter read all the code');
In this example we can understand that javascript interpreter reads the code one line at a time. The reason why browser will log 'I am side effect of this function' first is simply because waitThreeSeconds function executed before console.log('interpreter read all the code');
. If we would execute waitThreeSeconds after console.log('interpreter read all the code');
We would immediatly see 'interpreter read all the code' in the browser console.
But here is one thing, no matter when you click to the screen,'click event!' will be always final log because browser checks event queue only after execution stack is empty.
Top comments (0)