Home Web Front-end JS Tutorial Technical Interview Questions - Part Event Loop

Technical Interview Questions - Part Event Loop

Nov 29, 2024 am 11:45 AM

Introduction

Hello, everybody!

Today, as the title says ?, I’ll be talking about the event loop.

This is not a topic that interviewers often ask about directly (I can only remember two occasions when they asked me to explain the event loop). BUT, in most interviews, they ask questions that are related to it. For example:

  • "If I do this… what should be the behavior?"
  • "If my code looks like this, what will be the output?"
  • "Why does this code produce this output?"

All those questions are much easier to answer if you understand how the event loop works.

I'll be honest: this topic isn’t my favorite. I much prefer questions about the behavior of code rather than explaining how the event loop works for 10 minutes straight.?

Technical Interview Questions - Part  Event Loop

Let’s dive in! ?

## Questions
1. What is the event loop?
2. Examples


What is the event loop?

Short Answer:

The event loop is responsible for handling asynchronous tasks in the JavaScript runtime.

To be honest, I don’t think this answer is enough to satisfy the curiosity of an interviewer asking about the event loop. So, in this post, I’d like to dive deeper into this topic.

More than just knowing the concepts, it’s important to understand how it works. That’s why I’ve added some examples at the end.

Technical Interview Questions - Part  Event Loop

Theory

What is the Event Loop?

JavaScript has a runtime based on an event loop, which is responsible for handling tasks. Each language has a unique runtime, and an important point to note is that JavaScript is single-threaded.

What Does Single-Threaded Mean?

Single-threaded means that JavaScript can handle only one task at a time. This is why the event loop is so essential in JavaScript; it helps manage tasks efficiently despite this single-thread limitation.

Components of the Runtime

To understand the event loop better, let’s first look at its main components:

Technical Interview Questions - Part  Event Loop

Call Stack

The call stack is a data structure that keeps track of the functions we call. You can think of it like a stack of plates: when a function is called, it’s added to the stack, and when it finishes, it’s removed from the stack.

The call stack operates on a LIFO (Last-In-First-Out) principle, meaning JavaScript executes functions in the order they’re stacked—from the topmost item down to the bottom, one at a time (remember, JavaScript is single-threaded).

Queues

In JavaScript’s runtime, we have queues, which hold lists of tasks to be processed. Tasks in these queues wait until the call stack is empty.

  • Task Queue (or Callback Queue): This queue stores tasks like setTimeout() and setInterval() calls. Tasks here are processed after the call stack is empty and after all tasks in the Microtask Queue have been processed. See more examples of tasks that are stored in this queue on MDN.

  • Microtask Queue: This queue has priority over the Task Queue. It includes microtasks such as Promise callbacks and asynchronous functions like process.nextTick() and async functions.

The Task Queue works on a FIFO (First-In-First-Out) basis, meaning tasks are processed in the order they’re added, but only after the Microtask Queue is empty.

Event Loop

The event loop is a mechanism that manages the execution of asynchronous code. It observes the call stack and coordinates between the call stack and the queues (Task Queue and Microtask Queue) to keep the code running smoothly.

How Does It Work?

Let's go through the event loop process step by step. Refer to the image below for a visual representation.

Technical Interview Questions - Part  Event Loop

In this example:

  • The Call Stack has one function.
  • The Microtask Queue has two messages.
  • The Task Queue has one message.

Step 1: Process the Call Stack

  1. The event loop starts by looking at the Call Stack.
  2. It finds a function in the stack and begins executing it.
  3. Once this function completes, it is removed from the Call Stack.

Technical Interview Questions - Part  Event Loop

Step 2: Process the Microtask Queue

  1. After the Call Stack is empty, the event loop checks the Microtask Queue.
  2. It takes the first message from the Microtask Queue and pushes it to the Call Stack for execution.

Technical Interview Questions - Part  Event Loop

  1. The function runs and, once completed, is removed from the Call Stack.
  2. The event loop then moves to the next message in the Microtask Queue and repeats the process.
  3. This continues until there are no more messages left in the Microtask Queue.

Technical Interview Questions - Part  Event Loop

Step 3: Process the Task Queue

  1. Once both the Call Stack and the Microtask Queue are empty, the event loop turns to the Task Queue.
  2. It picks the first message in the Task Queue and adds it to the Call Stack.
  3. The function runs, and when it completes, it’s removed from the Call Stack.
  4. The event loop will continue this process with each task in the Task Queue, ensuring all tasks are handled one by one.

Technical Interview Questions - Part  Event Loop

By following this order—Call Stack, then Microtask Queue, and finally Task Queue—the event loop helps JavaScript handle asynchronous code efficiently, even within its single-threaded environment.


Examples

Now that we understand how the event loop works and how tasks are prioritized, let’s look at some examples.

Example 1

const a = new Promise(function showA(resolve){
  console.log('A');
  resolve('B');
});

setTimeout(function showC() {
  console.log('C');
}, 0);

a.then(function showB(b) {
  console.log(b);
});

const d = function showD() {
  console.log('D');
};

d();
Copy after login
Copy after login

Before continuing, try to think about the order of the output.

✨What do you expect it to be?✨

Let’s break down each part of the code to understand why we get this output.

1. Creating the Promise

const a = new Promise(function showA(resolve) {
  console.log('A');
  resolve('B');
});
Copy after login
Copy after login
  • Here, we create a new promise with a callback function.
  • Inside this function, console.log('A') is executed immediately, so "A" is printed to the console.
  • After logging "A", the promise is resolved with the value "B".
  • JavaScript recognizes there’s a .then callback (i.e., showB) that should run once the main call stack is clear, so it adds showB to the Microtask Queue (since promise resolutions go there).

2. setTimeout Call

setTimeout(function showC() {
  console.log('C');
}, 0);
Copy after login
Copy after login
  • The setTimeout function schedules showC to run after 0 milliseconds.
  • JavaScript places showC in the Task Queue because it’s a timer-based function.

3. a.then Callback

const a = new Promise(function showA(resolve){
  console.log('A');
  resolve('B');
});

setTimeout(function showC() {
  console.log('C');
}, 0);

a.then(function showB(b) {
  console.log(b);
});

const d = function showD() {
  console.log('D');
};

d();
Copy after login
Copy after login
  • This line registers a .then handler for the promise we already resolved in the previous step (resolve('B')).
  • Since the promise is resolved, showB (the .then callback) is added to the Microtask Queue.

4. Defining d

const a = new Promise(function showA(resolve) {
  console.log('A');
  resolve('B');
});
Copy after login
Copy after login
  • This line simply defines the function showD but doesn’t execute it yet, so nothing happens here.

5. Calling d()

setTimeout(function showC() {
  console.log('C');
}, 0);
Copy after login
Copy after login
  • Now, we call d(), which is added to the Call Stack and executed. This results in console.log('D'), so "D" is printed to the console.

Final Output Order:

a.then(function showB(b) {
  console.log(b);
});
Copy after login

GIF for reference

Technical Interview Questions - Part  Event Loop
Interactive Example

Example 2

const d = function showD() {
  console.log('D');
};
Copy after login

Again, take a moment to think about the order of the output.

✨What do you expect it to be?✨

Let's go with the explanation...

1. Logging "Start!"

d();
Copy after login
  • This line is added to the Call Stack and executed immediately.
  • As a result, "Start!" is printed to the console.
  1. setTimeout Call
A
D
B
C
Copy after login
  • The setTimeout function schedules showTimeout to run after 0 milliseconds.
  • JavaScript places showTimeout in the Task Queue since it’s a timer-based function.

3. Promise Resolution

console.log("Start!");

setTimeout(function showTimeout() {
  console.log("Timeout!");
}, 0);

Promise.resolve("Promise!")
  .then(function showPromise(res) {
    console.log(res);
  });

console.log("End!");
Copy after login
  • The promise is resolved immediately with the value "Promise!".
  • JavaScript places showPromise (the .then callback) in the Microtask Queue because promises go into the microtask queue after being resolved.

4. Logging "End!"

console.log("Start!");
Copy after login
  • This line is added to the Call Stack and executed immediately.
  • As a result, "End!" is printed to the console.

Final Output Order:

setTimeout(function showTimeout() {
  console.log("Timeout!");
}, 0);
Copy after login

GIF for reference

Technical Interview Questions - Part  Event Loop
Interactive Example

End

This chapter wasn’t too long, but I hope these examples helped you understand how the event loop works.

I strongly recommend experimenting with the interactive page to analyze other examples. Playing around on that page can make it much easier to understand the event loop in action.

Thank you so much for all the love on my previous posts!

See you next week! ?

Bye Bye

Technical Interview Questions - Part  Event Loop

The above is the detailed content of Technical Interview Questions - Part Event Loop. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

See all articles