SlideShare a Scribd company logo
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

PDF
JavaScript Event Loop
PPTX
JS Event Loop
PPTX
JavaScript Event Loop
PDF
Understanding the nodejs event loop
PDF
Introduction to kotlin coroutines
PPT
Spring Batch 2.0
PPT
JavaScript Event Loop
PPTX
JavaScript Promises
JavaScript Event Loop
JS Event Loop
JavaScript Event Loop
Understanding the nodejs event loop
Introduction to kotlin coroutines
Spring Batch 2.0
JavaScript Event Loop
JavaScript Promises

What's hot (20)

PDF
Coroutines for Kotlin Multiplatform in Practise
PPTX
JavaScript Engines and Event Loop
PPTX
Advanced JavaScript
PDF
RxJS Evolved
PDF
Angular Observables & RxJS Introduction
ODP
Introduction to Java 8
PDF
맛만 보자 액터 모델이란
PPTX
Understanding react hooks
PDF
NodeJS for Beginner
PPTX
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
PPT
Java Socket Programming
PPTX
Coroutines in Kotlin
PPTX
Java awt (abstract window toolkit)
PDF
JavaScript: Variables and Functions
PDF
Understanding the Single Thread Event Loop
PPTX
Rxjs ngvikings
PPTX
Java 8 Lambda and Streams
PPTX
Introduction à spring boot
PDF
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
PPTX
Exception handling in java
Coroutines for Kotlin Multiplatform in Practise
JavaScript Engines and Event Loop
Advanced JavaScript
RxJS Evolved
Angular Observables & RxJS Introduction
Introduction to Java 8
맛만 보자 액터 모델이란
Understanding react hooks
NodeJS for Beginner
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Java Socket Programming
Coroutines in Kotlin
Java awt (abstract window toolkit)
JavaScript: Variables and Functions
Understanding the Single Thread Event Loop
Rxjs ngvikings
Java 8 Lambda and Streams
Introduction à spring boot
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
Exception handling in java
Ad

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

PPTX
C#을 이용한 task 병렬화와 비동기 패턴
PPTX
Deep dumpster diving 2010
PDF
The Ring programming language version 1.7 book - Part 48 of 196
PDF
The Ring programming language version 1.5 book - Part 8 of 31
PDF
The Ring programming language version 1.5.3 book - Part 40 of 184
PDF
The Ring programming language version 1.5.4 book - Part 40 of 185
PDF
Node lt
PDF
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
PPT
JVM performance options. How it works
PPTX
JavaScript Multithread or Single Thread.pptx
PPTX
Parallel Processing
PDF
The Ring programming language version 1.10 book - Part 50 of 212
PDF
Introduction to Scalding and Monoids
PDF
A More Flash Like Web?
PPTX
Lambdas puzzler - Peter Lawrey
PDF
Refactoring to Macros with Clojure
PDF
V8 javascript engine for フロントエンドデベロッパー
PDF
Node.js - async for the rest of us.
PDF
The Ring programming language version 1.3 book - Part 84 of 88
PPT
Whats new in_csharp4
C#을 이용한 task 병렬화와 비동기 패턴
Deep dumpster diving 2010
The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.5 book - Part 8 of 31
The Ring programming language version 1.5.3 book - Part 40 of 184
The Ring programming language version 1.5.4 book - Part 40 of 185
Node lt
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
JVM performance options. How it works
JavaScript Multithread or Single Thread.pptx
Parallel Processing
The Ring programming language version 1.10 book - Part 50 of 212
Introduction to Scalding and Monoids
A More Flash Like Web?
Lambdas puzzler - Peter Lawrey
Refactoring to Macros with Clojure
V8 javascript engine for フロントエンドデベロッパー
Node.js - async for the rest of us.
The Ring programming language version 1.3 book - Part 84 of 88
Whats new in_csharp4
Ad

Recently uploaded (20)

PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
Pharma ospi slides which help in ospi learning
PPTX
Cell Structure & Organelles in detailed.
PDF
RMMM.pdf make it easy to upload and study
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
Complications of Minimal Access Surgery at WLH
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Pre independence Education in Inndia.pdf
PPTX
master seminar digital applications in india
PDF
Computing-Curriculum for Schools in Ghana
PDF
Insiders guide to clinical Medicine.pdf
PPTX
Cell Types and Its function , kingdom of life
PDF
Classroom Observation Tools for Teachers
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
102 student loan defaulters named and shamed – Is someone you know on the list?
TR - Agricultural Crops Production NC III.pdf
O7-L3 Supply Chain Operations - ICLT Program
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Pharma ospi slides which help in ospi learning
Cell Structure & Organelles in detailed.
RMMM.pdf make it easy to upload and study
STATICS OF THE RIGID BODIES Hibbelers.pdf
Complications of Minimal Access Surgery at WLH
Abdominal Access Techniques with Prof. Dr. R K Mishra
Pre independence Education in Inndia.pdf
master seminar digital applications in india
Computing-Curriculum for Schools in Ghana
Insiders guide to clinical Medicine.pdf
Cell Types and Its function , kingdom of life
Classroom Observation Tools for Teachers
FourierSeries-QuestionsWithAnswers(Part-A).pdf
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...

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/