SlideShare a Scribd company logo
4
Most read
13
Most read
All you need to know about the
JavaScript event loop
Saša Tatar @sasatatar
Front-end Dev at @codaxy
JavaScript Engine (e.g. V8)
• Heap
Objects are allocated in a heap which is just
a name to denote a large mostly
unstructured region of memory.
• Stack
Function calls form a stack of frames. Each
time a function is invoked, a new frame
containing its execution context (arguments
and local variables) is created and pushed
on top of the stack. Once the function
returns, the frame is popped off the stack.
Heap Stack
a first frame is created containing bar's arguments and local variables
The call stack
one thread => one call stack => one thing at a time
function foo(b) {
var a = 10;
debugger;
return a + b + 11;
}
function bar(x) {
var y = 3;
return foo(x * y);
}
bar(7);
Stack
(anonymous)
bar
foo
Call stack demo
Maximum call stack size excided => a.k.a. stack overflow
function foo(a) {
console.log(a++);
foo(a);
}
foo(0);
Stack
foo
foo
foo
foo
foo
foo
foo
JS Engine + Web API + Callback Queue
= JavaScript Runtime
Imagine a robot is playing a music:
• The JavaScript code would be the music notes to the
robot.
• The JavaScript engine would be the robot which can
understand the notes and act on it.
• The Web API would be the instruments the robot can
use in order to play the music.
Imagine a robot is putting out a fire:
• The JavaScript code would be the instructions for the
robot to put out a fire.
• The JavaScript engine would be the robot which can
understand the instructions and act on it.
• The Web API would be the fire truck, and the water
gun.
Stack
Web API
DOM
ajax
setTimeout
Callback Queue
Event loop - simplified
JavaScript Event Loop
Is queue
empty?
Process
one task
Is queue
empty?
No
Process
one task
Is rendering
needed?
Update
rendering
Yes
No
Yes
No
Yes
Macrotask queue
Microtask queue
DOM mutations Promises
Network
events
HTML
parsing
Keyboard
events
Mouse
events
Full loop completes at least every 16.67 ms.
callback
Example with setTimeout(callback, delay)
console.log(1);
setTimeout(function callback() {
console.log(2)
}, 0);
console.log(3);
stack
Web API
callback queue
(anonymous)
setTimeout(callback, 0);
callback
CONSOLE:
> 1
> 3
> 2
What about Promises?
function sleep(miliseconds) {
var currentTime = new Date().getTime();
while (currentTime + miliseconds >= new Date().getTime()) {
console.log('Doing some work (occupying the stack)...');
}
}
setTimeout(() => console.log('Timeout fires'), 0);
var p = new Promise((resolve, reject) => resolve());
sleep(200);
p.then(() => console.log('Promise resolved'));
JavaScript Event Loop
Is queue
empty?
Process
one task
Is queue
empty?
No
Process
one task
Is rendering
needed?
Update
rendering
Yes
No
Yes
No
Yes
Macrotask queue
Microtask queue
DOM mutations Promises
Network
events
HTML
parsing
Keyboard
events
Mouse
events
What about Promises?
function sleep(miliseconds) {
var currentTime = new Date().getTime();
while (currentTime + miliseconds >= new Date().getTime()) {
console.log('Doing some work (occupying the stack)...');
}
}
setTimeout(() => console.log('Timeout fires'), 0);
var p = new Promise((resolve, reject) => resolve());
sleep(200);
p.then(() => console.log('Promise resolved'));
Dealing with computationally expensive processing
// A long running task:
<table><tbody></tbody></table>
<script>
const tbody = document.querySelector("tbody");
for (let i = 0; i < 20000; i++) {
const tr = document.createElement("tr");
for (let t = 0; t < 6; t++) {
const td = document.createElement("td");
td.appendChild(document.createTextNode(i + "," + t));
tr.appendChild(td);
}
tbody.appendChild(tr);
}
</script>
creates an
individual row
for each row, creates 6
cells, each with a text node
attaches the new
row to its parent
Divide and conquer
const rowCount = 20000;
const divideInto = 4;
const chunkSize = rowCount/divideInto;
let iteration = 0;
const table = document.getElementsByTagName("tbody")[0];
setTimeout(function generateRows(){
const base = chunkSize * iteration;
for (let i = 0; i < chunkSize; i++) {
const tr = document.createElement("tr");
for (let t = 0; t < 6; t++) {
const td = document.createElement("td");
td.appendChild(
document.createTextNode((i + base) + "," + t + "," + iteration));
tr.appendChild(td);
}
table.appendChild(tr);
}
iteration++;
if (iteration < divideInto)
setTimeout(generateRows, 0);
}, 0);
We divide the rows in 4 smaller
chunks, 5000 rows each.
Compute where we left off last
time.
Schedules the next
phase
Set time-out delay to 0 to indicate that
the next iteration should execute ASAP,
but after the DOM has been updated.
Throttle and debounce
function throttle(callback, delay) {
let timer, context, args;
return function () {
context = this;
args = arguments;
if (!timer)
timer = setTimeout(function () {
callback.apply(context, args);
timer = null;
}, delay);
};
}
function debounce(callback, delay) {
let timer;
return function () {
let context = this,
args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
callback.apply(context, args);
}, delay);
};
}
That’s it!
Further reading/resources:
• https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop
• Philip Roberts: What the heck is the event loop anyway? | JSConf EU
• http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/
• Secrets of the JavaScript Ninja, J. Resig, B. Bibeault, J. Maras
• https://css-tricks.com/debouncing-throttling-explained-examples/

More Related Content

PPTX
JS Event Loop
Saai Vignesh P
 
PPTX
JavaScript Event Loop
Designveloper
 
PDF
JavaScript Event Loop
Derek Willian Stavis
 
PPT
JavaScript Event Loop
Thomas Hunter II
 
PDF
Understanding the nodejs event loop
Saurabh Kumar
 
PDF
Asynchronous JavaScript Programming with Callbacks & Promises
Hùng Nguyễn Huy
 
PPTX
JavaScript Engines and Event Loop
Tapan B.K.
 
PPTX
Introduction to Node js
Akshay Mathur
 
JS Event Loop
Saai Vignesh P
 
JavaScript Event Loop
Designveloper
 
JavaScript Event Loop
Derek Willian Stavis
 
JavaScript Event Loop
Thomas Hunter II
 
Understanding the nodejs event loop
Saurabh Kumar
 
Asynchronous JavaScript Programming with Callbacks & Promises
Hùng Nguyễn Huy
 
JavaScript Engines and Event Loop
Tapan B.K.
 
Introduction to Node js
Akshay Mathur
 

What's hot (20)

PPTX
Spring boot
sdeeg
 
PDF
The Integration of Laravel with Swoole
Albert Chen
 
PDF
Intro to Asynchronous Javascript
Garrett Welson
 
PDF
Introduction to Kotlin coroutines
Roman Elizarov
 
PDF
Asynchronous javascript
Eman Mohamed
 
PDF
Important React Hooks
Knoldus Inc.
 
PPT
Introduction To PHP
Shweta A
 
PPTX
Promises, Promises
Domenic Denicola
 
PPTX
Node.js Express
Eyal Vardi
 
ODP
Multithreading In Java
parag
 
PDF
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Edureka!
 
PPSX
Exception Handling
Reddhi Basu
 
PPTX
Angular Unit Testing
Alessandro Giorgetti
 
PPTX
PHP Presentation
JIGAR MAKHIJA
 
PDF
RxJS Evolved
trxcllnt
 
PPTX
Typescript ppt
akhilsreyas
 
PDF
Kotlin for Android Development
Speck&Tech
 
PPT
React js
Jai Santhosh
 
PDF
Introduction to kotlin coroutines
NAVER Engineering
 
Spring boot
sdeeg
 
The Integration of Laravel with Swoole
Albert Chen
 
Intro to Asynchronous Javascript
Garrett Welson
 
Introduction to Kotlin coroutines
Roman Elizarov
 
Asynchronous javascript
Eman Mohamed
 
Important React Hooks
Knoldus Inc.
 
Introduction To PHP
Shweta A
 
Promises, Promises
Domenic Denicola
 
Node.js Express
Eyal Vardi
 
Multithreading In Java
parag
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Edureka!
 
Exception Handling
Reddhi Basu
 
Angular Unit Testing
Alessandro Giorgetti
 
PHP Presentation
JIGAR MAKHIJA
 
RxJS Evolved
trxcllnt
 
Typescript ppt
akhilsreyas
 
Kotlin for Android Development
Speck&Tech
 
React js
Jai Santhosh
 
Introduction to kotlin coroutines
NAVER Engineering
 
Ad

Similar to All you need to know about the JavaScript event loop (20)

PPTX
JavaScript Multithread or Single Thread.pptx
RAHITNATH
 
PDF
The Evolution of Async-Programming (SD 2.0, JavaScript)
jeffz
 
PDF
JavaScript for real men
Ivano Malavolta
 
PDF
Douglas Crockford: Serversideness
WebExpo
 
PPTX
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Domenic Denicola
 
PDF
Beyond 60fps
Chris Thoburn
 
PDF
ES6: The Awesome Parts
Domenic Denicola
 
PPTX
[DevDay2018] How does JavaScript actually work? - By: Vi Nguyen, Senior Softw...
DevDay Da Nang
 
PPTX
Node.js - Advanced Basics
Doug Jones
 
PDF
Javascript under the hood
Ridhwana Khan
 
PDF
JavaScript
Ivano Malavolta
 
PDF
[2015/2016] JavaScript
Ivano Malavolta
 
PDF
Javascript internals
Ayush Sharma
 
PDF
Event Driven Javascript
Federico Galassi
 
PDF
JavaScript Async for Effortless UX
재석 강
 
PPT
Web development basics (Part-5)
Rajat Pratap Singh
 
PPTX
Events for JavaScript event loop track.pptx
sontinenianuradha
 
PDF
Event driven javascript
Francesca1980
 
PDF
Event driven javascript
Francesca1980
 
PDF
JS Fest 2019 Node.js Antipatterns
Timur Shemsedinov
 
JavaScript Multithread or Single Thread.pptx
RAHITNATH
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
jeffz
 
JavaScript for real men
Ivano Malavolta
 
Douglas Crockford: Serversideness
WebExpo
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Domenic Denicola
 
Beyond 60fps
Chris Thoburn
 
ES6: The Awesome Parts
Domenic Denicola
 
[DevDay2018] How does JavaScript actually work? - By: Vi Nguyen, Senior Softw...
DevDay Da Nang
 
Node.js - Advanced Basics
Doug Jones
 
Javascript under the hood
Ridhwana Khan
 
JavaScript
Ivano Malavolta
 
[2015/2016] JavaScript
Ivano Malavolta
 
Javascript internals
Ayush Sharma
 
Event Driven Javascript
Federico Galassi
 
JavaScript Async for Effortless UX
재석 강
 
Web development basics (Part-5)
Rajat Pratap Singh
 
Events for JavaScript event loop track.pptx
sontinenianuradha
 
Event driven javascript
Francesca1980
 
Event driven javascript
Francesca1980
 
JS Fest 2019 Node.js Antipatterns
Timur Shemsedinov
 
Ad

Recently uploaded (20)

PPTX
CDH. pptx
AneetaSharma15
 
PDF
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
PPTX
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
PDF
Health-The-Ultimate-Treasure (1).pdf/8th class science curiosity /samyans edu...
Sandeep Swamy
 
PPTX
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
PPTX
Care of patients with elImination deviation.pptx
AneetaSharma15
 
PPTX
Artificial-Intelligence-in-Drug-Discovery by R D Jawarkar.pptx
Rahul Jawarkar
 
PPTX
PREVENTIVE PEDIATRIC. pptx
AneetaSharma15
 
PDF
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
PPTX
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
PPTX
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
DOCX
Unit 5: Speech-language and swallowing disorders
JELLA VISHNU DURGA PRASAD
 
PDF
Types of Literary Text: Poetry and Prose
kaelandreabibit
 
PPTX
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
PPTX
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
PDF
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
PDF
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
DOCX
Action Plan_ARAL PROGRAM_ STAND ALONE SHS.docx
Levenmartlacuna1
 
PPTX
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
CDH. pptx
AneetaSharma15
 
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
Health-The-Ultimate-Treasure (1).pdf/8th class science curiosity /samyans edu...
Sandeep Swamy
 
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
Care of patients with elImination deviation.pptx
AneetaSharma15
 
Artificial-Intelligence-in-Drug-Discovery by R D Jawarkar.pptx
Rahul Jawarkar
 
PREVENTIVE PEDIATRIC. pptx
AneetaSharma15
 
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
Unit 5: Speech-language and swallowing disorders
JELLA VISHNU DURGA PRASAD
 
Types of Literary Text: Poetry and Prose
kaelandreabibit
 
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
Action Plan_ARAL PROGRAM_ STAND ALONE SHS.docx
Levenmartlacuna1
 
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 

All you need to know about the JavaScript event loop

  • 1. All you need to know about the JavaScript event loop Saša Tatar @sasatatar Front-end Dev at @codaxy
  • 2. JavaScript Engine (e.g. V8) • Heap Objects are allocated in a heap which is just a name to denote a large mostly unstructured region of memory. • Stack Function calls form a stack of frames. Each time a function is invoked, a new frame containing its execution context (arguments and local variables) is created and pushed on top of the stack. Once the function returns, the frame is popped off the stack. Heap Stack a first frame is created containing bar's arguments and local variables
  • 3. The call stack one thread => one call stack => one thing at a time function foo(b) { var a = 10; debugger; return a + b + 11; } function bar(x) { var y = 3; return foo(x * y); } bar(7); Stack (anonymous) bar foo
  • 5. Maximum call stack size excided => a.k.a. stack overflow function foo(a) { console.log(a++); foo(a); } foo(0); Stack foo foo foo foo foo foo foo
  • 6. JS Engine + Web API + Callback Queue = JavaScript Runtime Imagine a robot is playing a music: • The JavaScript code would be the music notes to the robot. • The JavaScript engine would be the robot which can understand the notes and act on it. • The Web API would be the instruments the robot can use in order to play the music. Imagine a robot is putting out a fire: • The JavaScript code would be the instructions for the robot to put out a fire. • The JavaScript engine would be the robot which can understand the instructions and act on it. • The Web API would be the fire truck, and the water gun. Stack Web API DOM ajax setTimeout Callback Queue Event loop - simplified
  • 7. JavaScript Event Loop Is queue empty? Process one task Is queue empty? No Process one task Is rendering needed? Update rendering Yes No Yes No Yes Macrotask queue Microtask queue DOM mutations Promises Network events HTML parsing Keyboard events Mouse events Full loop completes at least every 16.67 ms.
  • 8. callback Example with setTimeout(callback, delay) console.log(1); setTimeout(function callback() { console.log(2) }, 0); console.log(3); stack Web API callback queue (anonymous) setTimeout(callback, 0); callback CONSOLE: > 1 > 3 > 2
  • 9. What about Promises? function sleep(miliseconds) { var currentTime = new Date().getTime(); while (currentTime + miliseconds >= new Date().getTime()) { console.log('Doing some work (occupying the stack)...'); } } setTimeout(() => console.log('Timeout fires'), 0); var p = new Promise((resolve, reject) => resolve()); sleep(200); p.then(() => console.log('Promise resolved'));
  • 10. JavaScript Event Loop Is queue empty? Process one task Is queue empty? No Process one task Is rendering needed? Update rendering Yes No Yes No Yes Macrotask queue Microtask queue DOM mutations Promises Network events HTML parsing Keyboard events Mouse events
  • 11. What about Promises? function sleep(miliseconds) { var currentTime = new Date().getTime(); while (currentTime + miliseconds >= new Date().getTime()) { console.log('Doing some work (occupying the stack)...'); } } setTimeout(() => console.log('Timeout fires'), 0); var p = new Promise((resolve, reject) => resolve()); sleep(200); p.then(() => console.log('Promise resolved'));
  • 12. Dealing with computationally expensive processing // A long running task: <table><tbody></tbody></table> <script> const tbody = document.querySelector("tbody"); for (let i = 0; i < 20000; i++) { const tr = document.createElement("tr"); for (let t = 0; t < 6; t++) { const td = document.createElement("td"); td.appendChild(document.createTextNode(i + "," + t)); tr.appendChild(td); } tbody.appendChild(tr); } </script> creates an individual row for each row, creates 6 cells, each with a text node attaches the new row to its parent
  • 13. Divide and conquer const rowCount = 20000; const divideInto = 4; const chunkSize = rowCount/divideInto; let iteration = 0; const table = document.getElementsByTagName("tbody")[0]; setTimeout(function generateRows(){ const base = chunkSize * iteration; for (let i = 0; i < chunkSize; i++) { const tr = document.createElement("tr"); for (let t = 0; t < 6; t++) { const td = document.createElement("td"); td.appendChild( document.createTextNode((i + base) + "," + t + "," + iteration)); tr.appendChild(td); } table.appendChild(tr); } iteration++; if (iteration < divideInto) setTimeout(generateRows, 0); }, 0); We divide the rows in 4 smaller chunks, 5000 rows each. Compute where we left off last time. Schedules the next phase Set time-out delay to 0 to indicate that the next iteration should execute ASAP, but after the DOM has been updated.
  • 14. Throttle and debounce function throttle(callback, delay) { let timer, context, args; return function () { context = this; args = arguments; if (!timer) timer = setTimeout(function () { callback.apply(context, args); timer = null; }, delay); }; } function debounce(callback, delay) { let timer; return function () { let context = this, args = arguments; clearTimeout(timer); timer = setTimeout(function () { callback.apply(context, args); }, delay); }; }
  • 15. That’s it! Further reading/resources: • https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop • Philip Roberts: What the heck is the event loop anyway? | JSConf EU • http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/ • Secrets of the JavaScript Ninja, J. Resig, B. Bibeault, J. Maras • https://css-tricks.com/debouncing-throttling-explained-examples/