HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

What is the Event Loop in JavaScript?

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptwhateventloopthe

Problem

The Event Loop is a source of confusion for many developers, but it's a fundamental piece of the JavaScript engine. It's what allows JavaScript to be single-threaded, yet able to execute in a non-blocking fashion. To understand the Event Loop, we first need to explain a few things about the JavaScript engine, such as the Call Stack, Tasks, Microtasks and their respective Queues. Let's break them down one by one.
The Call Stack is a data structure that keeps track of the execution of JavaScript code. As the name suggests, it's a stack, thus a LIFO (Last In, First Out) data structure in memory. Each function that's executed is represented as a frame in the Call Stack and placed on top of the previous function.
Let's look at a simple example, step by step:
  1. The Call Stack is initially empty.
  2. The function foo() is pushed onto the Call Stack.

Solution

function foo() {
  console.log('foo');
  bar();
}

function bar() {
  console.log('bar');
}


Let's look at a simple example, step by step:
  1. The Call Stack is initially empty.
  2. The function foo() is pushed onto the Call Stack.
  3. The function foo() is executed and popped off the Call Stack.
  4. The function console.log('foo') is pushed onto the Call Stack.
  5. The function console.log('foo') is executed and popped off the Call Stack.

Code Snippets

function foo() {
  console.log('foo');
  bar();
}

function bar() {
  console.log('bar');
}
console.log('Script start');

setTimeout(() => console.log('setTimeout()'), 0);

Promise.resolve()
  .then(() => console.log('Promise.then() #1'))
  .then(() => console.log('Promise.then() #2'));

console.log('Script end');

// LOGS:
//   Script start
//   Script end
//   Promise.then() #1
//   Promise.then() #2
//   setTimeout()

Context

From 30-seconds-of-code: event-loop-explained

Revisions (0)

No revisions yet.