- The V8 engine has two parts:
- Memory Heap
- Call Stack
Call Stack: Within the call stack, your JS code is read and gets executed line by line.
Now, coming back to the previous question of how to use async call within JS. Within JS we have a lexical environment, syntax parser, an execution context (memory heap and call stack) that is used to execute the JS code. But except these browsers also have Event Loops, Callback queue, and WebAPIs that is also used to run the JS code. Although these are not the part of JS it also helps to execute the JS properly as we sometimes used the browser functions within the JS.
Let us take an example to be every clear of the concept. Suppose we have a following piece of code that we want to execute in the JS run-time environment.
A C B
When JS tries to execute the above program, it places the first statement in the call stack which gets executed and prints A in the console and it gets to pop out of the stack. Now, it places the second statement in the call stack and when it tries to execute the statement, it finds out that setTimeout() doesn’t belong to JS so it pops out the function and puts in the WebAPI to get executed there. Since the call stack is now again empty, it places the third statement in the stack and executes it thus prints C in the console.
In the meanwhile, the WebAPI executes the timeout function and places the code in the callback queue. The eventloop checks if the call stack is empty or not or whether there is any statement in the callback queue that needs to be executed all the time. As soon as event loop checks that call stack is empty and there is something in the callback queue that needs to be executed, it places the statement in the call stack and the call stack executes the statement and prints B in the console of the browser.
- Why is Parse Server the future of Backend As A Service?
- Why You Should Choose React Native?
- What is the best way to include CSS file? Why use @import?
- Why Node.js ?
- Why Linux Hosting is Cheaper than Windows Hosting ?
- Why Serverless Apps?
- Why do people prefer Selenium with Python?
- Why error "$ is not defined" occurred in jQuery ?
- Why require_once() function is so bad to use in PHP ?
- Why to put “_” in front of filename in SCSS ?
- Why does AngularJS include an empty option in select ?
- Why “chucknorris” is used as a color in HTML ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.