SlideShare a Scribd company logo
JS Event Loop
BY SAAI VIGNESH P
Agenda
• Before getting on to the main topic, we’ve
to re-iterate on:
• What is JavaScript?
• JS Runtime Environment
• Synchrony and Asynchrony
• Event Loop
• What is Event Loop?
• How it works?
• Why do we need it?
• Code Example Demonstration
What is JavaScript?
• JavaScript is a lightweight, cross-platform, and interpreted scripting language. It is used
for web development, both client-side and server-side.
• It is based on the ECMAScript Specification (ECMA-262 standard).
• The language is:
• Single Threaded (Synchronous)
• Event-driven (events are emitted and handled)
• Imperative (explicit instructions)
• Functional (creating and using functions)
JS Runtime Environment
• The JavaScript runtime environment provides access to built-in libraries and objects that
are available to a program so that it can interact with the outside world and make the code
work.
• The environment consists of:
• Execution Engine (Google V8)
• Web API – Browser; Low Level API – Node.js
• Callback Queue
• Event Loop
Synchrony and Asynchrony
Synchronous Calls:
• Code executes in the order they are called.
• The previous operation/function call should be
completed or done for the control to get transferred.
• i.e., they are blocking.
• Guess the output !
Output:
I’m Function 1
I’m Function 2
I’m Function 3
Explanation
Call Stack
Explanation
Call Stack
fun1()
Explanation
Call Stack
fun1()
Explanation
Call Stack
fun1()
console.log(“I’m Function 1”)
Output: I’m Function1
Explanation
Call Stack
fun1()
fun2()
Output: I’m Function1
Explanation
Call Stack
fun1()
fun2()
Output: I’m Function1
Explanation
Call Stack
fun1()
console.log(“I’m Function 2”)
fun2()
Output: I’m Function1
I’m Function 2
Explanation
Call Stack
fun1()
fun2()
fun3()
Output: I’m Function1
I’m Function 2
Explanation
Call Stack
fun1()
fun2()
fun3()
Output: I’m Function1
I’m Function 2
Explanation
Call Stack
fun1()
fun2()
fun3()
console.log(“I’m Function 3”)
Output: I’m Function1
I’m Function 2
I’m Function 3
Explanation
Call Stack
fun1()
fun2()
fun3()
Output: I’m Function1
I’m Function 2
I’m Function 3
Explanation
Call Stack
fun1()
fun2()
Output: I’m Function1
I’m Function 2
I’m Function 3
Explanation
Call Stack
fun1()
Output: I’m Function1
I’m Function 2
I’m Function 3
Explanation
Call Stack
Output: I’m Function1
I’m Function 2
I’m Function 3
Blocking Call Example
• Imagine downloading a 10 MB image from Internet with JavaScript, with an internet speed
of 1 MB/sec in a browser.
• It would ideally take 10 seconds to load the image.
• For these 10 seconds, no other operations can be done including rendering.
• Once download completes, rest of the operations can be executed.
• This is called a synchronous/blocking call.
• Solution: Async calls!
Synchrony and Asynchrony
Asynchronous Calls:
• Code executes and the control is returned no matter
whether the operation is completed or not.
• i.e., they are non-blocking.
• But how to know that they are complete? Use
callbacks!
Output:
Hello World
I’m JavaScript
Timeout!
Callbacks? What are they?
• A callback is a function passed into another function as an argument, which is then
invoked inside the function to complete some kind of routine or action.
• They are usually used with asynchronous operations. eg: background operations.
• Example:
setTimeout() and setInterval() works asynchronously.
Background Ops?
SOUNDS GOOD… BUT HOW??
Cause JavaScript is:
• Single Threaded, which means it has only one Call
Stack!!
One more confusion…
If JavaScript is Single Threaded,
Then how setTimeout() / setInterval() works?
Here’s where,
We’ve to know some facts…
Timer Functions & I/O
• JavaScript – No native asynchrony
• JavaScript does not have support for Timer and I/O, they’re not part of the language
(ECMAScript specification).
• Timer functions such as:
• setTimeout()
• setInterval()
• Input/output functions such as:
• console.log()
• console.error()
• Which means they are implemented by someone else.
• Who? It’s the runtime environment (Browser (Web API) / Node.js).
Remember this diagram?
JavaScript
Event Loop
• The event loop is a programming construct
or design pattern that waits for and
dispatches events or messages in a
program.
Source: Wikipedia
• It is by which the JavaScript language
behaves like a multi-threaded, being
single-threaded by nature.
• It is a form of concurrency achieved to
support asynchronous calls in JavaScript.
• So how it works? Let’s see…
Coding to demonstrate Event Loop
Try guessing the output?
Coding to demonstrate Event Loop
Try guessing the output?
Hello World
I’m JavaScript
Timeout!
Output:
Coding to demonstrate Event Loop
Try guessing the output?
Hello World
I’m JavaScript
Timeout!
Output: Hello World
I’m JavaScript
Timeout!
Output:
Let’s see how,
THAT STUFF HAPPENS…
Call Stack
Callback Queue
Event
Loop
Web API
Let’s take the example:
Start Execution!
Call Stack
Callback Queue
Event
Loop
Web API
Let’s take the example:
console.log(“Hello World”)
Executing…
Call Stack
Callback Queue
Event
Loop
Web API
Let’s take the example:
Timer()
Duration: 0ms
Callback: anonymous()
setTimeout(anonymous())
Executing…
Call Stack
Callback Queue
Event
Loop
Web API
Let’s take the example:
console.log(“I’m JavaScript’”)
Timer()
Duration: 0ms
Callback: anonymous()
COMPLETED
anonymous()
Executing…
Event Loop’s Job:
1. Check if call stack is empty.
2. If empty, pop the callback queue,
and push the callback function to
the call stack, else wait.
3. Execute the call stack.
Call Stack
Event
Loop
Web API
Let’s take the example:
anonymous()
anonymous()
Callback Queue
Executing…
Event Loop’s Job:
1. Check if call stack is empty.
2. If empty, pop the callback queue,
and push the callback function to
the call stack, else wait.
3. Execute the call stack.
Call Stack
Event
Loop
Web API
Let’s take the example:
anonymous()
Callback Queue
console.log(“Timeout!”)
Executing…
Event Loop’s Job:
1. Check if call stack is empty.
2. If empty, pop the callback queue,
and push the callback function to
the call stack, else wait.
3. Execute the call stack.
Call Stack
Event
Loop
Web API
Let’s take the example:
anonymous()
Callback Queue
Executing…
Event Loop’s Job:
1. Check if call stack is empty.
2. If empty, pop the callback queue,
and push the callback function to
the call stack, else wait.
3. Execute the call stack.
Call Stack
Event
Loop
Web API
Let’s take the example:
Callback Queue
Terminated
Event Loop’s Job:
1. Check if call stack is empty.
2. If empty, pop the callback queue,
and push the callback function to
the call stack, else wait.
3. Execute the call stack.
Synopsis of the Demo
• So event loop helps in concurrency of multiple operations. Yes it is true.
• But still JS is single-threaded and event loop has to wait for the call stack to get empty.
• Event Loop is also responsible for firing the callbacks associated with events.
• So JavaScript without it’s runtime having the event loop, and Web API, event handling or
asynchronous execution cannot be achieved.
• Call Stack and Events Demo: https://bit.ly/event-loop-demo
Why Asynchrony is needed?
• Asynchronous execution is needed, because Browsers!.
• Browser’s webpage rendering and JS execution engine runs on the same thread.
• So, if JS is busy executing some stuff, browser rendering is stuck until JS’s call stack gets empty.
• [Code Demo]
Fun Fact about Callbacks
• Callbacks need not be always asynchronous!
• Callback functions can also be synchronous.
• So which callbacks are asynchronous? Event handlers and Timers are.
• Which is not? Array.forEach()
• Custom callbacks need not be.
• For Example:
Array.forEach(callback) isn’t asynchronous.
https://bit.ly/array-foreach-demo
Thank You!
That’s how event handling and asynchrony works in JavaScript.
Thanks to Event Loop!

More Related Content

What's hot

JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
Derek Willian Stavis
 
Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)
Adnan Sohail
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & Promises
Hùng Nguyễn Huy
 
JavaScript Engines and Event Loop
JavaScript Engines and Event Loop JavaScript Engines and Event Loop
JavaScript Engines and Event Loop
Tapan B.K.
 
Asynchronous JavaScript Programming
Asynchronous JavaScript ProgrammingAsynchronous JavaScript Programming
Asynchronous JavaScript Programming
Haim Michael
 
Asynchronous javascript
 Asynchronous javascript Asynchronous javascript
Asynchronous javascript
Eman Mohamed
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
Joseph de Castelnau
 
gRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at SquaregRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at Square
Apigee | Google Cloud
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JS
Cakra Danu Sedayu
 
Node.js File system & Streams
Node.js File system & StreamsNode.js File system & Streams
Node.js File system & Streams
Eyal Vardi
 
Spring Boot
Spring BootSpring Boot
Spring Boot
Jiayun Zhou
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
Bhanuka Uyanage
 
Asynchronous programming
Asynchronous programmingAsynchronous programming
Asynchronous programming
Filip Ekberg
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
Akshay Mathur
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST API
Fabien Vauchelles
 
The Javascript Ecosystem
The Javascript EcosystemThe Javascript Ecosystem
The Javascript Ecosystem
Emmanuel Akinde
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
Purbarun Chakrabarti
 
Reactjs workshop (1)
Reactjs workshop (1)Reactjs workshop (1)
Reactjs workshop (1)
Ahmed rebai
 

What's hot (20)

JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & Promises
 
JavaScript Engines and Event Loop
JavaScript Engines and Event Loop JavaScript Engines and Event Loop
JavaScript Engines and Event Loop
 
Asynchronous JavaScript Programming
Asynchronous JavaScript ProgrammingAsynchronous JavaScript Programming
Asynchronous JavaScript Programming
 
Asynchronous javascript
 Asynchronous javascript Asynchronous javascript
Asynchronous javascript
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
gRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at SquaregRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at Square
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JS
 
Node.js File system & Streams
Node.js File system & StreamsNode.js File system & Streams
Node.js File system & Streams
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Ajax Presentation
Ajax PresentationAjax Presentation
Ajax Presentation
 
Asynchronous programming
Asynchronous programmingAsynchronous programming
Asynchronous programming
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST API
 
The Javascript Ecosystem
The Javascript EcosystemThe Javascript Ecosystem
The Javascript Ecosystem
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Reactjs workshop (1)
Reactjs workshop (1)Reactjs workshop (1)
Reactjs workshop (1)
 
Express node js
Express node jsExpress node js
Express node js
 

Similar to JS Event Loop

Javascript internals
Javascript internalsJavascript internals
Javascript internals
Ayush Sharma
 
Web development basics (Part-5)
Web development basics (Part-5)Web development basics (Part-5)
Web development basics (Part-5)
Rajat Pratap Singh
 
Rethinking the debugger
Rethinking the debuggerRethinking the debugger
Rethinking the debugger
Iulian Dragos
 
Basic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.js
Gary Yeh
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
jacekbecela
 
"Leveraging the Event Loop for Blazing-Fast Applications!", Michael Di Prisco
"Leveraging the Event Loop for Blazing-Fast Applications!",  Michael Di Prisco"Leveraging the Event Loop for Blazing-Fast Applications!",  Michael Di Prisco
"Leveraging the Event Loop for Blazing-Fast Applications!", Michael Di Prisco
Fwdays
 
Clojure Conj 2014 - Paradigms of core.async - Julian Gamble
Clojure Conj 2014 - Paradigms of core.async - Julian GambleClojure Conj 2014 - Paradigms of core.async - Julian Gamble
Clojure Conj 2014 - Paradigms of core.async - Julian Gamble
Julian Gamble
 
A first look into the Project Loom in Java
A first look into the Project Loom in JavaA first look into the Project Loom in Java
A first look into the Project Loom in Java
Lukas Steinbrecher
 
Node js internal
Node js internalNode js internal
Node js internal
Chinh Ngo Nguyen
 
JavaScript
JavaScriptJavaScript
JavaScript
Ivano Malavolta
 
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)jeffz
 
Fast, concurrent ruby web applications with EventMachine and EM::Synchrony
Fast, concurrent ruby web applications with EventMachine and EM::SynchronyFast, concurrent ruby web applications with EventMachine and EM::Synchrony
Fast, concurrent ruby web applications with EventMachine and EM::SynchronyKyle Drake
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
Chetan Giridhar
 
Reactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-JavaReactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-Java
Kasun Indrasiri
 
Why scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisWhy scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with this
Ruslan Shevchenko
 
IP Unit 2.pptx
IP Unit 2.pptxIP Unit 2.pptx
IP Unit 2.pptx
Vigneshkumar Ponnusamy
 
About Clack
About ClackAbout Clack
About Clack
fukamachi
 
C# Async/Await Explained
C# Async/Await ExplainedC# Async/Await Explained
C# Async/Await Explained
Jeremy Likness
 
Applying the paradigms of core.async in Clojure and ClojureScript
Applying the paradigms of core.async in Clojure and ClojureScriptApplying the paradigms of core.async in Clojure and ClojureScript
Applying the paradigms of core.async in Clojure and ClojureScript
Julian Gamble
 

Similar to JS Event Loop (20)

Javascript internals
Javascript internalsJavascript internals
Javascript internals
 
Web development basics (Part-5)
Web development basics (Part-5)Web development basics (Part-5)
Web development basics (Part-5)
 
Rethinking the debugger
Rethinking the debuggerRethinking the debugger
Rethinking the debugger
 
Basic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.js
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
"Leveraging the Event Loop for Blazing-Fast Applications!", Michael Di Prisco
"Leveraging the Event Loop for Blazing-Fast Applications!",  Michael Di Prisco"Leveraging the Event Loop for Blazing-Fast Applications!",  Michael Di Prisco
"Leveraging the Event Loop for Blazing-Fast Applications!", Michael Di Prisco
 
Clojure Conj 2014 - Paradigms of core.async - Julian Gamble
Clojure Conj 2014 - Paradigms of core.async - Julian GambleClojure Conj 2014 - Paradigms of core.async - Julian Gamble
Clojure Conj 2014 - Paradigms of core.async - Julian Gamble
 
A first look into the Project Loom in Java
A first look into the Project Loom in JavaA first look into the Project Loom in Java
A first look into the Project Loom in Java
 
Node js internal
Node js internalNode js internal
Node js internal
 
JavaScript
JavaScriptJavaScript
JavaScript
 
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
 
Fast, concurrent ruby web applications with EventMachine and EM::Synchrony
Fast, concurrent ruby web applications with EventMachine and EM::SynchronyFast, concurrent ruby web applications with EventMachine and EM::Synchrony
Fast, concurrent ruby web applications with EventMachine and EM::Synchrony
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
Reactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-JavaReactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-Java
 
Why scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisWhy scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with this
 
IP Unit 2.pptx
IP Unit 2.pptxIP Unit 2.pptx
IP Unit 2.pptx
 
Concurrency in ruby
Concurrency in rubyConcurrency in ruby
Concurrency in ruby
 
About Clack
About ClackAbout Clack
About Clack
 
C# Async/Await Explained
C# Async/Await ExplainedC# Async/Await Explained
C# Async/Await Explained
 
Applying the paradigms of core.async in Clojure and ClojureScript
Applying the paradigms of core.async in Clojure and ClojureScriptApplying the paradigms of core.async in Clojure and ClojureScript
Applying the paradigms of core.async in Clojure and ClojureScript
 

Recently uploaded

LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
mz5nrf0n
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
Boni García
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
Hironori Washizaki
 
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
kalichargn70th171
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
Roshan Dwivedi
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 

Recently uploaded (20)

LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
 
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 

JS Event Loop

  • 1. JS Event Loop BY SAAI VIGNESH P
  • 2. Agenda • Before getting on to the main topic, we’ve to re-iterate on: • What is JavaScript? • JS Runtime Environment • Synchrony and Asynchrony • Event Loop • What is Event Loop? • How it works? • Why do we need it? • Code Example Demonstration
  • 3. What is JavaScript? • JavaScript is a lightweight, cross-platform, and interpreted scripting language. It is used for web development, both client-side and server-side. • It is based on the ECMAScript Specification (ECMA-262 standard). • The language is: • Single Threaded (Synchronous) • Event-driven (events are emitted and handled) • Imperative (explicit instructions) • Functional (creating and using functions)
  • 4. JS Runtime Environment • The JavaScript runtime environment provides access to built-in libraries and objects that are available to a program so that it can interact with the outside world and make the code work. • The environment consists of: • Execution Engine (Google V8) • Web API – Browser; Low Level API – Node.js • Callback Queue • Event Loop
  • 5. Synchrony and Asynchrony Synchronous Calls: • Code executes in the order they are called. • The previous operation/function call should be completed or done for the control to get transferred. • i.e., they are blocking. • Guess the output !
  • 6. Output: I’m Function 1 I’m Function 2 I’m Function 3
  • 13. Explanation Call Stack fun1() console.log(“I’m Function 2”) fun2() Output: I’m Function1 I’m Function 2
  • 16. Explanation Call Stack fun1() fun2() fun3() console.log(“I’m Function 3”) Output: I’m Function1 I’m Function 2 I’m Function 3
  • 17. Explanation Call Stack fun1() fun2() fun3() Output: I’m Function1 I’m Function 2 I’m Function 3
  • 18. Explanation Call Stack fun1() fun2() Output: I’m Function1 I’m Function 2 I’m Function 3
  • 19. Explanation Call Stack fun1() Output: I’m Function1 I’m Function 2 I’m Function 3
  • 20. Explanation Call Stack Output: I’m Function1 I’m Function 2 I’m Function 3
  • 21. Blocking Call Example • Imagine downloading a 10 MB image from Internet with JavaScript, with an internet speed of 1 MB/sec in a browser. • It would ideally take 10 seconds to load the image. • For these 10 seconds, no other operations can be done including rendering. • Once download completes, rest of the operations can be executed. • This is called a synchronous/blocking call. • Solution: Async calls!
  • 22. Synchrony and Asynchrony Asynchronous Calls: • Code executes and the control is returned no matter whether the operation is completed or not. • i.e., they are non-blocking. • But how to know that they are complete? Use callbacks! Output: Hello World I’m JavaScript Timeout!
  • 23. Callbacks? What are they? • A callback is a function passed into another function as an argument, which is then invoked inside the function to complete some kind of routine or action. • They are usually used with asynchronous operations. eg: background operations. • Example: setTimeout() and setInterval() works asynchronously.
  • 24. Background Ops? SOUNDS GOOD… BUT HOW?? Cause JavaScript is: • Single Threaded, which means it has only one Call Stack!!
  • 25. One more confusion… If JavaScript is Single Threaded, Then how setTimeout() / setInterval() works?
  • 26. Here’s where, We’ve to know some facts…
  • 27. Timer Functions & I/O • JavaScript – No native asynchrony • JavaScript does not have support for Timer and I/O, they’re not part of the language (ECMAScript specification). • Timer functions such as: • setTimeout() • setInterval() • Input/output functions such as: • console.log() • console.error() • Which means they are implemented by someone else. • Who? It’s the runtime environment (Browser (Web API) / Node.js).
  • 29. JavaScript Event Loop • The event loop is a programming construct or design pattern that waits for and dispatches events or messages in a program. Source: Wikipedia • It is by which the JavaScript language behaves like a multi-threaded, being single-threaded by nature. • It is a form of concurrency achieved to support asynchronous calls in JavaScript. • So how it works? Let’s see…
  • 30.
  • 31. Coding to demonstrate Event Loop Try guessing the output?
  • 32. Coding to demonstrate Event Loop Try guessing the output? Hello World I’m JavaScript Timeout! Output:
  • 33. Coding to demonstrate Event Loop Try guessing the output? Hello World I’m JavaScript Timeout! Output: Hello World I’m JavaScript Timeout! Output:
  • 34. Let’s see how, THAT STUFF HAPPENS…
  • 35. Call Stack Callback Queue Event Loop Web API Let’s take the example: Start Execution!
  • 36. Call Stack Callback Queue Event Loop Web API Let’s take the example: console.log(“Hello World”) Executing…
  • 37. Call Stack Callback Queue Event Loop Web API Let’s take the example: Timer() Duration: 0ms Callback: anonymous() setTimeout(anonymous()) Executing…
  • 38. Call Stack Callback Queue Event Loop Web API Let’s take the example: console.log(“I’m JavaScript’”) Timer() Duration: 0ms Callback: anonymous() COMPLETED anonymous() Executing… Event Loop’s Job: 1. Check if call stack is empty. 2. If empty, pop the callback queue, and push the callback function to the call stack, else wait. 3. Execute the call stack.
  • 39. Call Stack Event Loop Web API Let’s take the example: anonymous() anonymous() Callback Queue Executing… Event Loop’s Job: 1. Check if call stack is empty. 2. If empty, pop the callback queue, and push the callback function to the call stack, else wait. 3. Execute the call stack.
  • 40. Call Stack Event Loop Web API Let’s take the example: anonymous() Callback Queue console.log(“Timeout!”) Executing… Event Loop’s Job: 1. Check if call stack is empty. 2. If empty, pop the callback queue, and push the callback function to the call stack, else wait. 3. Execute the call stack.
  • 41. Call Stack Event Loop Web API Let’s take the example: anonymous() Callback Queue Executing… Event Loop’s Job: 1. Check if call stack is empty. 2. If empty, pop the callback queue, and push the callback function to the call stack, else wait. 3. Execute the call stack.
  • 42. Call Stack Event Loop Web API Let’s take the example: Callback Queue Terminated Event Loop’s Job: 1. Check if call stack is empty. 2. If empty, pop the callback queue, and push the callback function to the call stack, else wait. 3. Execute the call stack.
  • 43. Synopsis of the Demo • So event loop helps in concurrency of multiple operations. Yes it is true. • But still JS is single-threaded and event loop has to wait for the call stack to get empty. • Event Loop is also responsible for firing the callbacks associated with events. • So JavaScript without it’s runtime having the event loop, and Web API, event handling or asynchronous execution cannot be achieved. • Call Stack and Events Demo: https://bit.ly/event-loop-demo
  • 44. Why Asynchrony is needed? • Asynchronous execution is needed, because Browsers!. • Browser’s webpage rendering and JS execution engine runs on the same thread. • So, if JS is busy executing some stuff, browser rendering is stuck until JS’s call stack gets empty. • [Code Demo]
  • 45. Fun Fact about Callbacks • Callbacks need not be always asynchronous! • Callback functions can also be synchronous. • So which callbacks are asynchronous? Event handlers and Timers are. • Which is not? Array.forEach() • Custom callbacks need not be. • For Example: Array.forEach(callback) isn’t asynchronous. https://bit.ly/array-foreach-demo
  • 46. Thank You! That’s how event handling and asynchrony works in JavaScript. Thanks to Event Loop!