The Magic Behind JavaScript's Asynchronous Programming
In The article how the JavaScript script is executed and what are the steps of execution script is explained. This article aim to explore how JavaScript handle asynchronous code. Before exploration is started there are some concepts should be explained.
Concepts
Synchronous: means the code is executed line by line. if there are 2 operations
console.log(1)
console.log(2)
The second log will not be started executing until first log is finished.
Asynchronous: means that tasks are executed parallel without blocking the main program.
Event queue: is FIFO (First In First Out) data structure which the completed asynchronous tasks or events are added in it.
JavaScript Architecture
JavaScript is single threaded so When JavaScript program is running all Synchronous code run in this thread so long running tasks should be avoided because if this thread be blocked there is no another tasks will be executed and the program will be frozen. But there are another threads to handle blocking tasks like ( HTTP calls, Timers or IO operations, ...) and this threads managed by Libuv (in NodeJS ) or Web API (in browser).
The execution flow
When the program is started, each function invocation pushed to call stack and if this function is synchronous, the execution is continued . If this function is asynchronous (IO operations/ timer..) this task is delegated to Libuv/ web ApIs to be handled then next function pushed to call stack and so on tell the call stack is empty, in parallel the asynchronous tasks are executing and after one finished the callback function pushed in the event queue and the event loop make continues check on call stack till be empty then take callback function from event queue and push it to call stack to start execution this process continue till the call stack and event queue are empty the the program terminated.
Example
function add(a, b) {
return a + b;
}
Console.log("Started");
setTimeout(() => {
console.log("Timer is finished");
}, 5000);
console.log("Ended");
Output
Started
Ended
Timer is finished
Execution steps
领英推荐
Conclusion
JavaScript is single threaded and this thread must not be blocked and it can handle blocking code by delegating it to another threads (Libuv/ Web API).