How asynchronous JavaScript code gets executed in browser ?
Last Updated :
07 Apr, 2021
Functions or operations that are running in parallel with the other functions or operations are called the asynchronous functions or operations in JavaScript. Asynchronous functions use Callback Functions that get executed later. Let us see an example that demonstrates this:
JavaScript
setTimeout(function greet() {
console.log("Welcome to GeeksforGeeks!");
}, 2000);
In the above example, setTimeout is the asynchronous function and uses the callback function greet with a delay of 2000 milliseconds. Therefore, after the timer gets expired, the message gets printed in the console. Now, let's see how the above operation gets executed in the JavaScript engine of a browser.
Behind the scenes of execution of asynchronous JavaScript:
The JavaScript code gets executed by a Call Stack and as the Call Stack does not contain anything like a timer, we cannot delay the code execution. Therefore, for performing an asynchronous operations, we use the help of a web API setTimeout() which is available in the window global object in the browser.
Interestingly setTimeout is not a part of JavaScript, it is one of the many web APIs (Eg: setTImeout, DOM APIs, fetch, LocalStorage, console, location etc.) that are available in the global object of the browser. Browsers give the JavaScript engine the ability to access these web APIs through this global object. And, because window is a global object we can access the web APIs without the window keyword.
To see the behind the scene workings of asynchronous code getting executed in the browser, let us first see an example of asynchronous code.
Example:
JavaScript
setTimeout(function greet(){
console.log("Welcome to GeeksforGeeks!");
}, 2000);
console.log("Hi!");
Here, setTimeout registers the callback function greet in the web API environment and attaches a timer with 2 seconds time. Now as everything JavaScript gets executed by Call Stack, the JavaScript engine will first create a Global Execution Context and will execute the last line and print "Hi!" in the console.
Execution of asynchronous JavaScript operation in browser
Once the execution is finished the Global Execution Context gets removed from the Call Stack. Now, after the timer gets expired, to print the greeting message we need to somehow fetch the callback function greet to the Call Stack in order to execute. This is done by Event Loop and Callback Queue.
After the timer gets expired, the callback function is put inside the Callback Queue and the job of the Event Loop is to check if the Call Stack is empty and if empty, push the callback function from Callback Queue to Call Stack and the callback function gets removed from the Callback Queue. Then the Call Stack creates an Execution Context of the call back function and executes it. Â
Execution of asynchronous JavaScript operation in browser
Therefore, the output of the code will be:
Hi!
Welcome to GeeksforGeeks!
The second line will be displayed after the 2 seconds of delay. This is how an asynchronous operation in JavaScript gets executed behind the scene in the browser.
Similar Reads
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
What is an API (Application Programming Interface) In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read
Introduction of Firewall in Computer Network A firewall is a network security device either hardware or software-based which monitors all incoming and outgoing traffic and based on a defined set of security rules it accepts, rejects, or drops that specific traffic. It acts like a security guard that helps keep your digital world safe from unwa
10 min read