Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Event Queue in JavaScript
Next article icon

Event Queue in JavaScript

Last Updated : 15 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

JavaScript, being single-threaded, processes tasks sequentially, meaning it executes one task at a time. This can pose a challenge when dealing with operations that take time to complete, such as fetching data from a server or performing complex calculations. To handle such scenarios efficiently, JavaScript employs asynchronous behavior.

The-Secret-Behind-Steady-App-Performance-Asynchronous-JavaScript1
The Async JavaScript

Call Stack

The call stack is a mechanism that JavaScript uses to keep track of its execution context. Whenever a function is invoked, a corresponding frame is pushed onto the call stack. This frame contains information about the function's arguments, local variables, and the line of code currently being executed. Once a function completes its execution, its frame is popped off the stack.

Asynchronous Behavior

Asynchronous behavior allows JavaScript to execute non-blocking code. This means that instead of waiting for a time-consuming operation to complete, JavaScript can continue executing other tasks while waiting for the result. Common examples of asynchronous operations include fetching data from an API, reading files, or executing setTimeout.

When an asynchronous operation is encountered, it is off loaded to the browser's APIs (such as XMLHttpRequest, setTimeout, or fetch) to handle. JavaScript continues executing other tasks in the meantime.

Event Queue and Event Loop

The-Secret-Behind-Steady-App-Performance-Asynchronous-JavaScript-(1)
Event queue and Event loop

While JavaScript is busy executing other tasks, the asynchronous operation is carried out by the browser in the background. Once the operation is completed, its result is placed in the event queue.

The event loop continuously monitors the call stack and the event queue. When the call stack is empty (i.e., there are no pending synchronous tasks), the event loop picks the first item from the event queue and pushes it onto the call stack for execution. This process ensures that asynchronous tasks are executed in the order they were completed, without blocking the main thread. So the asynchronous function like setTimeout in this case is executed after all synchronous code.

Example: To demonstrate the asynchronous nature of the JavaScript using the setTimeut.

JavaScript
console.log("First part")  setTimeout(() => {     console.log("Second part") }     , 500) //waits for 0.5s (Asyncronous code)  console.log("Third part") 

Output
First part Third part Second part 

Example: To demonstrate the asynchronous nature of the JavaScript using the setTimeout method.

JavaScript
console.log("First part")  setTimeout(() => {     console.log("Second part") }     , 0) //waits for 0s(Asyncronous code)  console.log("Third part") 

Output
First part Third part Second part 

The result of the asnychronous part was available immediately but the output is printed last. It is because all the asynchronous code is executed after all syncronous code.

Example: To demonstrate the working of the Asynch JavaScript in event loop.

JavaScript
console.log("First part")  setTimeout(() => {     console.log("Second part") }     , 0) //waits for 0s(Asyncronous code)  setTimeout(() => {     console.log("Second 2 part") }     , 0) //waits for 0s(Asyncronous code)  console.log("Third part") 

Output
First part Third part Second part Second 2 part 

In JavaScript event queues, micro and macro task queues play crucial roles in managing asynchronous operations. Here's an overview of each:

Microtask Queue

Microtasks are tasks that are executed asynchronously, but right after the currently executing script. They are usually high-priority tasks and are often used for things like promises and mutation observers.

In JavaScript, the microtask queue is commonly implemented using the Promise object. When a promise settles (fulfilled or rejected), its respective .then() and .catch() handlers are placed in the microtask queue.

Example: To demonstrate the micro task queue working using the console.log('End') statement that comes after the promises, it's logged before the microtasks because microtasks execute immediately after the current task is done executing.

JavaScript
console.log('Start');  Promise.resolve().then(() => {     console.log('Microtask 1') }); Promise.resolve().then(() => {     console.log('Microtask 2') });  console.log('End'); 

Output
Start End Microtask 1 Microtask 2 

Macro Task Queue

Macrotasks are tasks that are executed asynchronously, but they are placed at the end of the event queue and executed after the microtasks. Common examples of macrotasks include setTimeout, setInterval, and DOM event handlers. In JavaScript, the macro task queue includes tasks like setTimeout, setInterval, and I/O operations.

Example: To demonsrtate the working of the Macro task queue in JavaScript.

JavaScript
console.log('Start');  setTimeout(() => console.log('Macro task 1'), 0); setTimeout(() => console.log('Macro task 2'), 0);  console.log('End'); 

Output
Start End Macro task 1 Macro task 2 

Implementation in Event Queue:

The event loop in JavaScript handles both microtasks and macrotasks. When an event occurs, it's placed in the appropriate queue. Microtasks are executed first, followed by macrotasks.

Example: To demonstrate the working of the micro and macro task queue in JavaScript.

JavaScript
console.log('Start');  Promise.resolve().then(() => console.log('Microtask 1')); setTimeout(() => console.log('Macro task 1'), 0);  console.log('End'); 

Output
Start End Microtask 1 Macro task 1 

Micro tasks have higher priority and are executed before macro tasks in the JavaScript event loop. They are often used for critical operations like handling promises or observing mutations. Macro tasks, on the other hand, are deferred tasks that are executed after micro tasks and are commonly associated with I/O events and timers.

JavaScript
console.log("Start");  setTimeout(() => {   console.log("Inside setTimeout->1 (macrotask)"); }, 0);  Promise.resolve().then(() => {   console.log("Inside Promise.then->1 (microtask)"); });  Promise.resolve().then(() => {   console.log("Inside Promise.then->2 (microtask)"); });  setTimeout(() => {   console.log("Inside setTimeout->2 (macrotask)"); }, 0);  console.log("End"); 

Output
Start End Inside Promise.then->1 (microtask) Inside Promise.then->2 (microtask) Inside setTimeout->1 (macrotask) Inside setTimeout->2 (macrotask) 

The order of execution:

  • "Start" is logged.
  • Two setTimeout functions and two promise .then() functions are scheduled.
  • "End of the script" is logged.
  • Microtasks are executed. Both Promise.then() functions are executed in the order they were scheduled. So, "Inside Promise.then 1 (microtask)" and "Inside Promise.then 2 (microtask)" are logged.
  • Macrotasks are executed. Both setTimeout functions are executed in the order they were scheduled. So, "Inside setTimeout 1 (macrotask)" and "Inside setTimeout 2 (macrotask)" are logged.

This demonstrates the execution order of tasks in both microtask and macrotask queues.


Next Article
Event Queue in JavaScript

T

tanishbhushan
Improve
Article Tags :
  • JavaScript
  • Web Technologies

Similar Reads

    Timing Events in Javascript
    Timing events are the events that help to execute a piece of code at a specific time interval. These events are directly available in the HTML DOM (Document Object Model) Window object, i.e., they are present in the browser. So, these are called global methods and can be invoked through the 'window'
    5 min read
    JavaScript Events
    JavaScript Events are actions or occurrences that happen in the browser. They can be triggered by various user interactions or by the browser itself. HTML<html> <script> function myFun() { document.getElementById( "gfg").innerHTML = "GeeksforGeeks"; } </script> <body> <but
    3 min read
    JavaScript onmouse Events
    The onmouse event is used to define the operation using the mouse. JavaScript onmouse events are: onmouseover and onmouseoutonmouseup and onmousedownonmouseenter and onmouseleave JavaScript onmouseover and onmouseout: The onmouseover and onmouseout events occur when the mouse cursor is placed over s
    1 min read
    Pointer Events in Javascript DOM
    Pointer events are a set of DOM (Document Object Model) events that provide a unified way of handling inputs from a variety of devices, such as touchscreens, mouse, and pen/stylus. These events are supported by modern browsers and allow developers to write code that responds to user interactions wit
    5 min read
    How to trigger events in JavaScript ?
    JavaScript is a high-level, interpreted, dynamically typed client-side scripting language. While HTML is static and defines the structure of a web page, JavaScript adds interactivity and functionality to HTML elements. This interaction is facilitated through events, which are actions or occurrences
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences