SlideShare una empresa de Scribd logo
1 de 46
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!

Más contenido relacionado

La actualidad más candente

JavaScript - Chapter 3 - Introduction
 JavaScript - Chapter 3 - Introduction JavaScript - Chapter 3 - Introduction
JavaScript - Chapter 3 - IntroductionWebStackAcademy
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous JavascriptGarrett Welson
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 
JavaScript Engines and Event Loop
JavaScript Engines and Event Loop JavaScript Engines and Event Loop
JavaScript Engines and Event Loop Tapan B.K.
 
JavaScript Fetch API
JavaScript Fetch APIJavaScript Fetch API
JavaScript Fetch APIXcat Liu
 
ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptWojciech Dzikowski
 
Asynchronous javascript
 Asynchronous javascript Asynchronous javascript
Asynchronous javascriptEman Mohamed
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slidesSmithss25
 
Introduction to react_js
Introduction to react_jsIntroduction to react_js
Introduction to react_jsMicroPyramid .
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and StatementsWebStackAcademy
 

La actualidad más candente (20)

Javascript functions
Javascript functionsJavascript functions
Javascript functions
 
JavaScript - Chapter 3 - Introduction
 JavaScript - Chapter 3 - Introduction JavaScript - Chapter 3 - Introduction
JavaScript - Chapter 3 - Introduction
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
JavaScript Engines and Event Loop
JavaScript Engines and Event Loop JavaScript Engines and Event Loop
JavaScript Engines and Event Loop
 
Modern JS with ES6
Modern JS with ES6Modern JS with ES6
Modern JS with ES6
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
 
Callback Function
Callback FunctionCallback Function
Callback Function
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Javascript
JavascriptJavascript
Javascript
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
JavaScript Fetch API
JavaScript Fetch APIJavaScript Fetch API
JavaScript Fetch API
 
ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern Javascript
 
Asynchronous javascript
 Asynchronous javascript Asynchronous javascript
Asynchronous javascript
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slides
 
Spring Batch 2.0
Spring Batch 2.0Spring Batch 2.0
Spring Batch 2.0
 
Introduction to react_js
Introduction to react_jsIntroduction to react_js
Introduction to react_js
 
React hooks
React hooksReact hooks
React hooks
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
 

Similar a JS Event Loop

Javascript internals
Javascript internalsJavascript internals
Javascript internalsAyush 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 debuggerIulian 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.jsGary Yeh
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsjacekbecela
 
"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 PriscoFwdays
 
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 GambleJulian 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 JavaLukas Steinbrecher
 
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 pythonChetan 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-JavaKasun 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 thisRuslan Shevchenko
 
C# Async/Await Explained
C# Async/Await ExplainedC# Async/Await Explained
C# Async/Await ExplainedJeremy 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 ClojureScriptJulian Gamble
 

Similar a 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
 

Último

Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencessuser9e7c64
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfmaor17
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdfAndrey Devyatkin
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesKrzysztofKkol1
 

Último (20)

Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conference
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdf
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
 

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!