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…
JS Event Loop
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 (20)

All you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopAll you need to know about the JavaScript event loop
All you need to know about the JavaScript event loop
Saša Tatar
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
Thomas Hunter II
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
Derek Willian Stavis
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
L&T Technology Services Limited
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko
 
Typescript ppt
Typescript pptTypescript ppt
Typescript ppt
akhilsreyas
 
TypeScript - An Introduction
TypeScript - An IntroductionTypeScript - An Introduction
TypeScript - An Introduction
NexThoughts Technologies
 
Ajax Presentation
Ajax PresentationAjax Presentation
Ajax Presentation
alaa.moustafa
 
Callback Function
Callback FunctionCallback Function
Callback Function
Roland San Nicolas
 
React hooks
React hooksReact hooks
React hooks
Ramy ElBasyouni
 
Reactjs
ReactjsReactjs
Reactjs
Mallikarjuna G D
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
Rob Eisenberg
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
Nir Elbaz
 
ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern Javascript
Wojciech Dzikowski
 
Expressjs
ExpressjsExpressjs
Expressjs
Yauheni Nikanovich
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
Tariqul islam
 
Angular and The Case for RxJS
Angular and The Case for RxJSAngular and The Case for RxJS
Angular and The Case for RxJS
Sandi Barr
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
Derek Willian Stavis
 
Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?
FITC
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
DivyanshGupta922023
 

Similar to JS Event Loop (20)

Javascript internals
Javascript internalsJavascript internals
Javascript internals
Ayush Sharma
 
JavaScript Engines and Event Loop
JavaScript Engines and Event Loop JavaScript Engines and Event Loop
JavaScript Engines and Event Loop
Tapan B.K.
 
The evolution of asynchronous javascript
The evolution of asynchronous javascriptThe evolution of asynchronous javascript
The evolution of asynchronous javascript
Alessandro Cinelli (cirpo)
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
NodeXperts
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
Ivano Malavolta
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
Amitai Barnea
 
JavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxJavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptx
RAHITNATH
 
Javascript why what and how
Javascript why what and howJavascript why what and how
Javascript why what and how
sureshpraja1234
 
Async discussion 9_29_15
Async discussion 9_29_15Async discussion 9_29_15
Async discussion 9_29_15
Cheryl Yaeger
 
The JavaScript Event Loop - Concurrency in the Language of the Web
The JavaScript Event Loop - Concurrency in the Language of the WebThe JavaScript Event Loop - Concurrency in the Language of the Web
The JavaScript Event Loop - Concurrency in the Language of the Web
marukochan23
 
Understanding the nodejs event loop
Understanding the nodejs event loopUnderstanding the nodejs event loop
Understanding the nodejs event loop
Saurabh Kumar
 
Events for JavaScript event loop track.pptx
Events for JavaScript event loop track.pptxEvents for JavaScript event loop track.pptx
Events for JavaScript event loop track.pptx
sontinenianuradha
 
Developing Async Sense
Developing Async SenseDeveloping Async Sense
Developing Async Sense
Nemanja Stojanovic
 
Javascript: Behind the scenes.pdf
Javascript: Behind the scenes.pdfJavascript: Behind the scenes.pdf
Javascript: Behind the scenes.pdf
ShubhamChaurasia88
 
Async js
Async jsAsync js
Async js
lahin31
 
JavaScript
JavaScriptJavaScript
JavaScript
Ivano Malavolta
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
Ivano Malavolta
 
Event Driven Javascript
Event Driven JavascriptEvent Driven Javascript
Event Driven Javascript
Federico Galassi
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
jnewmanux
 
Web development basics (Part-5)
Web development basics (Part-5)Web development basics (Part-5)
Web development basics (Part-5)
Rajat Pratap Singh
 
Javascript internals
Javascript internalsJavascript internals
Javascript internals
Ayush Sharma
 
JavaScript Engines and Event Loop
JavaScript Engines and Event Loop JavaScript Engines and Event Loop
JavaScript Engines and Event Loop
Tapan B.K.
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
NodeXperts
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
Amitai Barnea
 
JavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxJavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptx
RAHITNATH
 
Javascript why what and how
Javascript why what and howJavascript why what and how
Javascript why what and how
sureshpraja1234
 
Async discussion 9_29_15
Async discussion 9_29_15Async discussion 9_29_15
Async discussion 9_29_15
Cheryl Yaeger
 
The JavaScript Event Loop - Concurrency in the Language of the Web
The JavaScript Event Loop - Concurrency in the Language of the WebThe JavaScript Event Loop - Concurrency in the Language of the Web
The JavaScript Event Loop - Concurrency in the Language of the Web
marukochan23
 
Understanding the nodejs event loop
Understanding the nodejs event loopUnderstanding the nodejs event loop
Understanding the nodejs event loop
Saurabh Kumar
 
Events for JavaScript event loop track.pptx
Events for JavaScript event loop track.pptxEvents for JavaScript event loop track.pptx
Events for JavaScript event loop track.pptx
sontinenianuradha
 
Javascript: Behind the scenes.pdf
Javascript: Behind the scenes.pdfJavascript: Behind the scenes.pdf
Javascript: Behind the scenes.pdf
ShubhamChaurasia88
 
Async js
Async jsAsync js
Async js
lahin31
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
jnewmanux
 
Web development basics (Part-5)
Web development basics (Part-5)Web development basics (Part-5)
Web development basics (Part-5)
Rajat Pratap Singh
 
Ad

Recently uploaded (20)

Feeling Lost in the Blue? Exploring a New Path: AI Mental Health Counselling ...
Feeling Lost in the Blue? Exploring a New Path: AI Mental Health Counselling ...Feeling Lost in the Blue? Exploring a New Path: AI Mental Health Counselling ...
Feeling Lost in the Blue? Exploring a New Path: AI Mental Health Counselling ...
officeiqai
 
Design by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First DevelopmentDesign by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First Development
Par-Tec S.p.A.
 
BoxLang-Dynamic-AWS-Lambda by Luis Majano.pdf
BoxLang-Dynamic-AWS-Lambda by Luis Majano.pdfBoxLang-Dynamic-AWS-Lambda by Luis Majano.pdf
BoxLang-Dynamic-AWS-Lambda by Luis Majano.pdf
Ortus Solutions, Corp
 
Rebuilding Cadabra Studio: AI as Our Core Foundation
Rebuilding Cadabra Studio: AI as Our Core FoundationRebuilding Cadabra Studio: AI as Our Core Foundation
Rebuilding Cadabra Studio: AI as Our Core Foundation
Cadabra Studio
 
How John started to like TDD (instead of hating it) (ViennaJUG, June'25)
How John started to like TDD (instead of hating it) (ViennaJUG, June'25)How John started to like TDD (instead of hating it) (ViennaJUG, June'25)
How John started to like TDD (instead of hating it) (ViennaJUG, June'25)
Nacho Cougil
 
Micro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Micro-Metrics Every Performance Engineer Should Validate Before Sign-OffMicro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Micro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Tier1 app
 
Custom Software Development: Types, Applications and Benefits.pdf
Custom Software Development: Types, Applications and Benefits.pdfCustom Software Development: Types, Applications and Benefits.pdf
Custom Software Development: Types, Applications and Benefits.pdf
Digital Aptech
 
Top 10 Mobile Banking Apps in the USA.pdf
Top 10 Mobile Banking Apps in the USA.pdfTop 10 Mobile Banking Apps in the USA.pdf
Top 10 Mobile Banking Apps in the USA.pdf
LL Technolab
 
War Story: Removing Offensive Language from Percona Toolkit
War Story: Removing Offensive Language from Percona ToolkitWar Story: Removing Offensive Language from Percona Toolkit
War Story: Removing Offensive Language from Percona Toolkit
Sveta Smirnova
 
Boost Student Engagement with Smart Attendance Software for Schools
Boost Student Engagement with Smart Attendance Software for SchoolsBoost Student Engagement with Smart Attendance Software for Schools
Boost Student Engagement with Smart Attendance Software for Schools
Visitu
 
zOS CommServer support for the Network Express feature on z17
zOS CommServer support for the Network Express feature on z17zOS CommServer support for the Network Express feature on z17
zOS CommServer support for the Network Express feature on z17
zOSCommserver
 
Techdebt handling with cleancode focus and as risk taker
Techdebt handling with cleancode focus and as risk takerTechdebt handling with cleancode focus and as risk taker
Techdebt handling with cleancode focus and as risk taker
RajaNagendraKumar
 
Oliveira2024 - Combining GPT and Weak Supervision.pdf
Oliveira2024 - Combining GPT and Weak Supervision.pdfOliveira2024 - Combining GPT and Weak Supervision.pdf
Oliveira2024 - Combining GPT and Weak Supervision.pdf
GiliardGodoi1
 
Content Mate Web App Triples Content Managers‘ Productivity
Content Mate Web App Triples Content Managers‘ ProductivityContent Mate Web App Triples Content Managers‘ Productivity
Content Mate Web App Triples Content Managers‘ Productivity
Alex Vladimirovich
 
How AI Can Improve Media Quality Testing Across Platforms (1).pptx
How AI Can Improve Media Quality Testing Across Platforms (1).pptxHow AI Can Improve Media Quality Testing Across Platforms (1).pptx
How AI Can Improve Media Quality Testing Across Platforms (1).pptx
kalichargn70th171
 
Shortcomings of EHS Software – And How to Overcome Them
Shortcomings of EHS Software – And How to Overcome ThemShortcomings of EHS Software – And How to Overcome Them
Shortcomings of EHS Software – And How to Overcome Them
TECH EHS Solution
 
AI-ASSISTED METAMORPHIC TESTING FOR DOMAIN-SPECIFIC MODELLING AND SIMULATION
AI-ASSISTED METAMORPHIC TESTING FOR DOMAIN-SPECIFIC MODELLING AND SIMULATIONAI-ASSISTED METAMORPHIC TESTING FOR DOMAIN-SPECIFIC MODELLING AND SIMULATION
AI-ASSISTED METAMORPHIC TESTING FOR DOMAIN-SPECIFIC MODELLING AND SIMULATION
miso_uam
 
How a Staff Augmentation Company IN USA Powers Flutter App Breakthroughs.pdf
How a Staff Augmentation Company IN USA Powers Flutter App Breakthroughs.pdfHow a Staff Augmentation Company IN USA Powers Flutter App Breakthroughs.pdf
How a Staff Augmentation Company IN USA Powers Flutter App Breakthroughs.pdf
mary rojas
 
Online Queue Management System for Public Service Offices [Focused on Municip...
Online Queue Management System for Public Service Offices [Focused on Municip...Online Queue Management System for Public Service Offices [Focused on Municip...
Online Queue Management System for Public Service Offices [Focused on Municip...
Rishab Acharya
 
List Unfolding - 'unfold' as the Computational Dual of 'fold', and how 'unfol...
List Unfolding - 'unfold' as the Computational Dual of 'fold', and how 'unfol...List Unfolding - 'unfold' as the Computational Dual of 'fold', and how 'unfol...
List Unfolding - 'unfold' as the Computational Dual of 'fold', and how 'unfol...
Philip Schwarz
 
Feeling Lost in the Blue? Exploring a New Path: AI Mental Health Counselling ...
Feeling Lost in the Blue? Exploring a New Path: AI Mental Health Counselling ...Feeling Lost in the Blue? Exploring a New Path: AI Mental Health Counselling ...
Feeling Lost in the Blue? Exploring a New Path: AI Mental Health Counselling ...
officeiqai
 
Design by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First DevelopmentDesign by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First Development
Par-Tec S.p.A.
 
BoxLang-Dynamic-AWS-Lambda by Luis Majano.pdf
BoxLang-Dynamic-AWS-Lambda by Luis Majano.pdfBoxLang-Dynamic-AWS-Lambda by Luis Majano.pdf
BoxLang-Dynamic-AWS-Lambda by Luis Majano.pdf
Ortus Solutions, Corp
 
Rebuilding Cadabra Studio: AI as Our Core Foundation
Rebuilding Cadabra Studio: AI as Our Core FoundationRebuilding Cadabra Studio: AI as Our Core Foundation
Rebuilding Cadabra Studio: AI as Our Core Foundation
Cadabra Studio
 
How John started to like TDD (instead of hating it) (ViennaJUG, June'25)
How John started to like TDD (instead of hating it) (ViennaJUG, June'25)How John started to like TDD (instead of hating it) (ViennaJUG, June'25)
How John started to like TDD (instead of hating it) (ViennaJUG, June'25)
Nacho Cougil
 
Micro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Micro-Metrics Every Performance Engineer Should Validate Before Sign-OffMicro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Micro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Tier1 app
 
Custom Software Development: Types, Applications and Benefits.pdf
Custom Software Development: Types, Applications and Benefits.pdfCustom Software Development: Types, Applications and Benefits.pdf
Custom Software Development: Types, Applications and Benefits.pdf
Digital Aptech
 
Top 10 Mobile Banking Apps in the USA.pdf
Top 10 Mobile Banking Apps in the USA.pdfTop 10 Mobile Banking Apps in the USA.pdf
Top 10 Mobile Banking Apps in the USA.pdf
LL Technolab
 
War Story: Removing Offensive Language from Percona Toolkit
War Story: Removing Offensive Language from Percona ToolkitWar Story: Removing Offensive Language from Percona Toolkit
War Story: Removing Offensive Language from Percona Toolkit
Sveta Smirnova
 
Boost Student Engagement with Smart Attendance Software for Schools
Boost Student Engagement with Smart Attendance Software for SchoolsBoost Student Engagement with Smart Attendance Software for Schools
Boost Student Engagement with Smart Attendance Software for Schools
Visitu
 
zOS CommServer support for the Network Express feature on z17
zOS CommServer support for the Network Express feature on z17zOS CommServer support for the Network Express feature on z17
zOS CommServer support for the Network Express feature on z17
zOSCommserver
 
Techdebt handling with cleancode focus and as risk taker
Techdebt handling with cleancode focus and as risk takerTechdebt handling with cleancode focus and as risk taker
Techdebt handling with cleancode focus and as risk taker
RajaNagendraKumar
 
Oliveira2024 - Combining GPT and Weak Supervision.pdf
Oliveira2024 - Combining GPT and Weak Supervision.pdfOliveira2024 - Combining GPT and Weak Supervision.pdf
Oliveira2024 - Combining GPT and Weak Supervision.pdf
GiliardGodoi1
 
Content Mate Web App Triples Content Managers‘ Productivity
Content Mate Web App Triples Content Managers‘ ProductivityContent Mate Web App Triples Content Managers‘ Productivity
Content Mate Web App Triples Content Managers‘ Productivity
Alex Vladimirovich
 
How AI Can Improve Media Quality Testing Across Platforms (1).pptx
How AI Can Improve Media Quality Testing Across Platforms (1).pptxHow AI Can Improve Media Quality Testing Across Platforms (1).pptx
How AI Can Improve Media Quality Testing Across Platforms (1).pptx
kalichargn70th171
 
Shortcomings of EHS Software – And How to Overcome Them
Shortcomings of EHS Software – And How to Overcome ThemShortcomings of EHS Software – And How to Overcome Them
Shortcomings of EHS Software – And How to Overcome Them
TECH EHS Solution
 
AI-ASSISTED METAMORPHIC TESTING FOR DOMAIN-SPECIFIC MODELLING AND SIMULATION
AI-ASSISTED METAMORPHIC TESTING FOR DOMAIN-SPECIFIC MODELLING AND SIMULATIONAI-ASSISTED METAMORPHIC TESTING FOR DOMAIN-SPECIFIC MODELLING AND SIMULATION
AI-ASSISTED METAMORPHIC TESTING FOR DOMAIN-SPECIFIC MODELLING AND SIMULATION
miso_uam
 
How a Staff Augmentation Company IN USA Powers Flutter App Breakthroughs.pdf
How a Staff Augmentation Company IN USA Powers Flutter App Breakthroughs.pdfHow a Staff Augmentation Company IN USA Powers Flutter App Breakthroughs.pdf
How a Staff Augmentation Company IN USA Powers Flutter App Breakthroughs.pdf
mary rojas
 
Online Queue Management System for Public Service Offices [Focused on Municip...
Online Queue Management System for Public Service Offices [Focused on Municip...Online Queue Management System for Public Service Offices [Focused on Municip...
Online Queue Management System for Public Service Offices [Focused on Municip...
Rishab Acharya
 
List Unfolding - 'unfold' as the Computational Dual of 'fold', and how 'unfol...
List Unfolding - 'unfold' as the Computational Dual of 'fold', and how 'unfol...List Unfolding - 'unfold' as the Computational Dual of 'fold', and how 'unfol...
List Unfolding - 'unfold' as the Computational Dual of 'fold', and how 'unfol...
Philip Schwarz
 
Ad

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…
  • 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!