0% found this document useful (0 votes)
4 views19 pages

Lecture 21 Event Loop in Nodejs - Copy

The document explains the event loop in Node.js, emphasizing its role in handling asynchronous operations without blocking the main thread. It details how the event loop, call stack, and callback queue work together to ensure efficient execution of tasks, allowing Node.js to manage multiple users simultaneously. Additionally, it highlights the importance of the EventEmitter class in responding to events within the application.

Uploaded by

artimist0611
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views19 pages

Lecture 21 Event Loop in Nodejs - Copy

The document explains the event loop in Node.js, emphasizing its role in handling asynchronous operations without blocking the main thread. It details how the event loop, call stack, and callback queue work together to ensure efficient execution of tasks, allowing Node.js to manage multiple users simultaneously. Additionally, it highlights the importance of the EventEmitter class in responding to events within the application.

Uploaded by

artimist0611
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Understanding the Event Loop

Session No.: 21
Course Name: Full Stack Development Using React and
Node.JS
Course Code: E1UA207B

Galgotias University 1
Recap

• What is Asynchronous Programming?

• Explain event-driven model.

• Name the core component for implementing event-

driven logic.

Galgotias University 2
Reflection:
• Asynchronous programming: In Node.js,
asynchronous programming means it can handle many
tasks at the same time without waiting for one to
finish before starting another. For example, while
reading a file or calling an API, Node.js can keep doing
other work. This makes it fast and efficient, especially
for web servers.

Galgotias University 3
Reflection:
• The event-driven model means the program waits
and listens for events (like a user click or file read),
and then responds by running specific functions
called event handlers. It helps apps stay responsive and
efficient.

• Core component: EventEmitter class

Galgotias University 4
Engaging Question
Question: “Node.js runs on a single thread. So how
does it handle thousands of users at once without
crashing or slowing down?”

Answer: By applying asynchronous programming


and event loop

Galgotias University 5
At the end of this session students will be able to

Understand event loop

Understand the
working of event loop
Galgotias University 6
• Event loop in Node.js
• Event loop and asynchronous
programming
• Activity: Think, pair and share
Session • How event loop works?
Outline

Galgotias University 7
Event Loop in Node.js
• The event loop is the core engine in Node.js that
handles asynchronous operations like file reading,
API calls, and timers — without blocking the main
thread.
• Even though Node.js runs on a single thread, the
event loop allows it to handle multiple tasks
efficiently by delegating long-running operations
(like file I/O or network requests) to the system, and
waiting for their completion in the background.

Galgotias University 8
Let’s see a simple Asynchronous example
• First statement is logged
console.log("This is the first statement"); immediately.
setTimeout(function() {
console.log("This is the second statement"); • setTimeout schedules the second
}, 1000); statement to log after 1000
milliseconds.
console.log("This is the third statement");
• Third statement is logged
immediately after.
Output:
This is the first statement • After 1000 milliseconds, the
This is the third statement callback from setTimeout is
This is the second statement executed, logging Second
statement.
Galgotias University 9
Activity: Think, pair and share
console.log("A");
setTimeout(() => { console.log("B");}, 1000);
console.log("C");

In what order will this print: A, B, C? Or A, C, B? Why?

Solution: A, C, B. It is because of the event loop


that moves the second statement to run in
background because of the waiting period.
Galgotias University 10
Activity Continue: Predict the output
console.log('Start');

setTimeout(() => {
console.log('Timer 1');
}, 2000);

setTimeout(() => {
console.log('Timer 2');
}, 1000);

console.log('End');
Galgotias University 11
Events and Event Loop
In Node.js, an event is a signal or notification that something has happened in the
application—such as a file being read, a timer completing, or a user action occurring.

Events are handled using Node’s EventEmitter system, allowing developers to define
custom responses to specific occurrences.

On the other hand, the event loop is the core mechanism that continuously monitors
the call stack and the callback queue to manage and schedule asynchronous operations.

While events define what should happen when something occurs, the event loop controls
when it should happen, ensuring non-blocking execution by handling these events and
their associated callbacks efficiently.

Together, they form the foundation of Node.js’s asynchronous, event-


driven architecture. Galgotias University 12
Event Loop System (Simple Analogy)
Imagine a chef (CPU) in a kitchen who can only cook one dish at a
time.

Call Stack (Immediate Tasks): This is like the chef's main table — he
puts one dish at a time here to cook immediately.

Callback Queue (Waiting Tasks): This is like a side shelf — dishes


that need to wait for something (like baking time, delivery, etc.) go here.

Event Loop
• The chef's assistant who keeps checking:
• Is the main table (call stack) empty?
• If yes, move one waiting task from the shelf (callback queue) to the table
to cook
Galgotias University 13
Call Stack and callback queue

console.log("This is the first statement");


setTimeout(function() {
console.log("This is the second
statement");
}, 1000);

console.log("This is the third statement");


Output:
This is the first statement
This is the third statement
This is the second statement

•The call stack runs immediate code line by line.


•Delayed or background tasks like setTimeout wait in the callback queue.
•When the main work is done, the event loop brings tasks from the queue to the stack.

Galgotias University 14
Event Loop in more details
• The event loop in Node.js is a mechanism that allows
asynchronous tasks to be handled efficiently without
blocking the execution of other operations. It:
• Executes JavaScript synchronously first and then
processes asynchronous operations.
• Delegates heavy tasks like I/O operations, timers, and
network requests to the libuv library.
• Ensures smooth execution of multiple operations by
queuing and scheduling callbacks efficiently.

Galgotias University 15
Traditional
Feature Node.js Event Loop
Multithreading
Single-threaded (JS
Thread Model Multi-threaded
execution)
Concurrency Event loop with
Multiple threads
Mechanism callbacks/promises
Non-blocking via async Can be blocking unless
Blocking I/O
APIs async I/O used
Heavier (more
Lightweight (fewer
Resource Usage memory/thread
threads)
overhead)
Easier for I/O-bound Easier for CPU-bound
Ease of Use
apps parallelism
Less common (no Common (needs
Race Conditions
shared memory)
Galgotias University
synchronization) 16
Summary
JavaScript is single-threaded: It runs one command at a time using the call stack.

Asynchronous operations don't block the code: Tasks like setTimeout, fs.readFile,
or fetch() are handled outside the main thread.

Call Stack: Where all the functions are run immediately, one by one.
Callback Queue: Once an async task is complete, its callback function is queued
here.

Event Loop: It continuously checks:


•If the call stack is empty, it moves the first task from the callback queue into
the call stack.
•This keeps apps non-blocking
•Your app stays responsive while waiting for slow tasks.
Galgotias University 17
Post Session Assignment
• Submit the wooflash assignment of
lecture 21 on LMS.

Galgotias University 18
Information to next topic of
the course
Introduction to JSON

Galgotias University 19

You might also like