Leveraging the Event Loop for Blazing-Fast Applications!

Rate this content
Bookmark

Some weeks ago I made my own implementation of signals, capable of updating 300k times the DOM in circa 600ms. Leveraging the Microtask Queue, I was able to bring that number down to 6ms, effectively improving performances by 100x. I wanna share how the Microtask Queue works and how you can leverage the Event Loop to improve performances.

FAQ

Michael Di Brisco, also known as Kadevan on the web, is a senior developer at Jointly. He is also an open source contributor and a junior father at home.

The main topics of the talk include the event loop, the microtask queue, and a live demo on how these concepts are implemented and utilized in JavaScript.

The event loop is a mechanism in JavaScript that orchestrates the execution order of events, handling the call stack, and managing asynchronous operations through the microtask and macro task queues.

The microtask queue in JavaScript is a queue for tasks that should be executed after the current operation completes and before control is yielded back to the event loop, allowing finer-grained control over asynchronous operations.

The microtask queue handles operations that are processed immediately after the current script runs and before the next event loop cycle starts, while the macro task queue schedules tasks that are processed on subsequent ticks of the event loop, allowing for UI rendering and other browser tasks to intervene.

JavaScript is considered single-threaded because it has a single call stack and executes code in a single thread. However, it can perform non-blocking operations using asynchronous callbacks, making it capable of handling tasks like a multi-threaded environment.

While both environments use the V8 engine, their capabilities differ mainly in the APIs they provide. For example, Node.js can interact with the file system, while browsers provide APIs like the DOM that are specific to web pages.

Yes, improper use of the microtask queue can lead to performance issues like infinite loops or blocked main threads, as it prioritizes microtasks over other tasks including rendering, potentially leading to delayed visual updates.

The microtask queue is useful for optimizing performance by managing the execution order of operations that need to be run immediately after the current stack but before the next rendering. It's particularly beneficial in batching operations and avoiding unnecessary re-renders in frameworks like React.

Michael Di Prisco
Michael Di Prisco
35 min
20 Oct, 2023

Comments

Sign in or register to post your comment.
  • Michael Di Prisco
    Michael Di Prisco
    Jointly
    Hey everyone, in my implementation I did a little mistake on stage, sorry for that. If you move the boolean at row 34 outside the callback (Row 33) at 18:27 you will effectively achieve the 100x performance improvement you were all waiting for! Sorry but the anxiety of the moment made me make a mistake there ;)

Video Summary and Transcription

This talk covers the event loop, microtask queue, and provides a live demo. JavaScript is single-threaded but can perform tasks that only a multithreaded environment can. The event loop consists of a call stack and microtask queue, which allow JavaScript to run non-blocking operations. Leveraging the microtask queue can lead to significant performance improvements in applications, such as React. However, it is important to use it correctly to avoid issues like infinite loops.

1. Introduction to Event Loop and Microtask Queue

Short description:

I'm Michael Di Brisco, known as Kadevan, a senior developer in Jointly and an open source contributor. Today, we will cover three main topics: the event loop, the microtask queue, and a live demo. JavaScript is both single-threaded and not. We'll explore this further. The ECMAScript specification does not allow for multithreading.

I hope you are enjoying London since now. It's raining, but it's a lovely city. So, as Jessica said, I'm Michael Di Brisco, known on the web as Kadevan, I'm a senior developer in Jointly and I'm a junior father at home and I'm also an open source contributor. But I'm not the main part of this talk so first of all, sorry for my English and I'm Italian so yeah, whatever.

And let's go to our table of contents. So what are we going to talk about today? We have three main topics we want to cover. Of course, we will not dive deep into all of them because we have 90 minutes, as I can see. So we will talk about what is the event loop. So we briefly talk about it. We will then talk about the microtask queue. So our main topic will be that one. So we go deep dive into the microtask queue and then we will go live demo. As we all know, live demo always go well during events. So I promised you learn something. Yeah. So someone had to make some bad jokes and I decided that was me. And please raise your hand if you know what the microtask queue is. Okay. Yeah. Let's hope they are a little more later.

Okay. So let's start with a couple of premises. So one step back before starting our real journey. Let's try to answer two important questions today. So is JavaScript single-threaded? Yes and no. But yes. So you know that many of us work with React, okay? So we work in a browser. Some of us also work in Node. And you know you can leverage multiple threads. But the ECMAScript specification, let's say the list of rules around the language, do not allow for multithreading.

2. JavaScript Runtime and Engine

Short description:

So in fact, JavaScript is single-threaded. Yet it can do things that only a multithreaded environment could allow it to do. JavaScript runs in a box composed of two parts: the engine (e.g., Chrome V8) and the runtime (set of APIs on top of the engine). The browser and Node.js share the same parser and executor, but they have different APIs. For example, Node.js has the file system API, while the browser provides web APIs like the DOM.

So in fact, JavaScript is single-threaded. Yet it can do things that only a multithreaded environment could allow it to do. So first of all, let's answer this question. So what is a JavaScript runtime? Let's say JavaScript runs in some sort of box, container, let's call it how we want, and it's mainly composed of two parts. We have the engine and the runtime. The engine is, for example, the Chrome V8 engine. So it's the part that parses and executes our code and makes sure everything is in order and launches all of our code. And then we have the runtime. The runtime is the set of APIs on top of what the engine can do. So let's take the most famous duo in the JavaScript ecosystem, which are, of course, the browser and the node, and we will specifically talk about Chrome browser. Why that? Because they share both Chrome and V8, and the node shares the V8 engine. So we have something in common. The parser and executor of the code is the same, but, of course, the node and the browser are, well, different beasts, okay? So in node, you have, for example, the file system API. You can call the file system, ask for files, directories, etc., which is something you can't do. You can't do with the exact same API on the browser because the browser provides its own set of web APIs. Let's think about the DOM. You can't interact with the DOM in node because it's not part of the engine. The console.log, for example. Did you know there are two different implementations of the console.log? So it's not a specific part of the engine but it's provided by the runtimes. Okay. So now that we settled all those two questions, so we said that JavaScript is single threaded yet node isn't. Chrome isn't.

QnA

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

A Guide to React Rendering Behavior
React Advanced Conference 2022React Advanced Conference 2022
25 min
A Guide to React Rendering Behavior
Top Content
React is a library for "rendering" UI from components, but many users find themselves confused about how React rendering actually works. What do terms like "rendering", "reconciliation", "Fibers", and "committing" actually mean? When do renders happen? How does Context affect rendering, and how do libraries like Redux cause updates? In this talk, we'll clear up the confusion and provide a solid foundation for understanding when, why, and how React renders. We'll look at: - What "rendering" actually is - How React queues renders and the standard rendering behavior - How keys and component types are used in rendering - Techniques for optimizing render performance - How context usage affects rendering behavior| - How external libraries tie into React rendering
Don't Solve Problems, Eliminate Them
React Advanced Conference 2021React Advanced Conference 2021
39 min
Don't Solve Problems, Eliminate Them
Top Content
Humans are natural problem solvers and we're good enough at it that we've survived over the centuries and become the dominant species of the planet. Because we're so good at it, we sometimes become problem seekers too–looking for problems we can solve. Those who most successfully accomplish their goals are the problem eliminators. Let's talk about the distinction between solving and eliminating problems with examples from inside and outside the coding world.
Scaling Up with Remix and Micro Frontends
Remix Conf Europe 2022Remix Conf Europe 2022
23 min
Scaling Up with Remix and Micro Frontends
Top Content
Do you have a large product built by many teams? Are you struggling to release often? Did your frontend turn into a massive unmaintainable monolith? If, like me, you’ve answered yes to any of those questions, this talk is for you! I’ll show you exactly how you can build a micro frontend architecture with Remix to solve those challenges.
Speeding Up Your React App With Less JavaScript
React Summit 2023React Summit 2023
32 min
Speeding Up Your React App With Less JavaScript
Top Content
Too much JavaScript is getting you down? New frameworks promising no JavaScript look interesting, but you have an existing React application to maintain. What if Qwik React is your answer for faster applications startup and better user experience? Qwik React allows you to easily turn your React application into a collection of islands, which can be SSRed and delayed hydrated, and in some instances, hydration skipped altogether. And all of this in an incremental way without a rewrite.
React Concurrency, Explained
React Summit 2023React Summit 2023
23 min
React Concurrency, Explained
Top Content
React 18! Concurrent features! You might’ve already tried the new APIs like useTransition, or you might’ve just heard of them. But do you know how React 18 achieves the performance wins it brings with itself? In this talk, let’s peek under the hood of React 18’s performance features: - How React 18 lowers the time your page stays frozen (aka TBT) - What exactly happens in the main thread when you run useTransition() - What’s the catch with the improvements (there’s no free cake!), and why Vue.js and Preact straight refused to ship anything similar
The Future of Performance Tooling
JSNation 2022JSNation 2022
21 min
The Future of Performance Tooling
Top Content
Our understanding of performance & user-experience has heavily evolved over the years. Web Developer Tooling needs to similarly evolve to make sure it is user-centric, actionable and contextual where modern experiences are concerned. In this talk, Addy will walk you through Chrome and others have been thinking about this problem and what updates they've been making to performance tools to lower the friction for building great experiences on the web.

Workshops on related topic

React Performance Debugging Masterclass
React Summit 2023React Summit 2023
170 min
React Performance Debugging Masterclass
Top Content
Featured WorkshopFree
Ivan Akulov
Ivan Akulov
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
React, TypeScript, and TDD
React Advanced Conference 2021React Advanced Conference 2021
174 min
React, TypeScript, and TDD
Top Content
Featured WorkshopFree
Paul Everitt
Paul Everitt
ReactJS is wildly popular and thus wildly supported. TypeScript is increasingly popular, and thus increasingly supported.

The two together? Not as much. Given that they both change quickly, it's hard to find accurate learning materials.

React+TypeScript, with JetBrains IDEs? That three-part combination is the topic of this series. We'll show a little about a lot. Meaning, the key steps to getting productive, in the IDE, for React projects using TypeScript. Along the way we'll show test-driven development and emphasize tips-and-tricks in the IDE.
Web3 Workshop - Building Your First Dapp
React Advanced Conference 2021React Advanced Conference 2021
145 min
Web3 Workshop - Building Your First Dapp
Top Content
Featured WorkshopFree
Nader Dabit
Nader Dabit
In this workshop, you'll learn how to build your first full stack dapp on the Ethereum blockchain, reading and writing data to the network, and connecting a front end application to the contract you've deployed. By the end of the workshop, you'll understand how to set up a full stack development environment, run a local node, and interact with any smart contract using React, HardHat, and Ethers.js.
Remix Fundamentals
React Summit 2022React Summit 2022
136 min
Remix Fundamentals
Top Content
Featured WorkshopFree
Kent C. Dodds
Kent C. Dodds
Building modern web applications is riddled with complexity And that's only if you bother to deal with the problems
Tired of wiring up onSubmit to backend APIs and making sure your client-side cache stays up-to-date? Wouldn't it be cool to be able to use the global nature of CSS to your benefit, rather than find tools or conventions to avoid or work around it? And how would you like nested layouts with intelligent and performance optimized data management that just works™?
Remix solves some of these problems, and completely eliminates the rest. You don't even have to think about server cache management or global CSS namespace clashes. It's not that Remix has APIs to avoid these problems, they simply don't exist when you're using Remix. Oh, and you don't need that huge complex graphql client when you're using Remix. They've got you covered. Ready to build faster apps faster?
At the end of this workshop, you'll know how to:- Create Remix Routes- Style Remix applications- Load data in Remix loaders- Mutate data with forms and actions
Vue3: Modern Frontend App Development
Vue.js London Live 2021Vue.js London Live 2021
169 min
Vue3: Modern Frontend App Development
Top Content
Featured WorkshopFree
Mikhail Kuznetcov
Mikhail Kuznetcov
The Vue3 has been released in mid-2020. Besides many improvements and optimizations, the main feature of Vue3 brings is the Composition API – a new way to write and reuse reactive code. Let's learn more about how to use Composition API efficiently.

Besides core Vue3 features we'll explain examples of how to use popular libraries with Vue3.

Table of contents:
- Introduction to Vue3
- Composition API
- Core libraries
- Vue3 ecosystem

Prerequisites:
IDE of choice (Inellij or VSC) installed
Nodejs + NPM
Developing Dynamic Blogs with SvelteKit & Storyblok: A Hands-on Workshop
JSNation 2023JSNation 2023
174 min
Developing Dynamic Blogs with SvelteKit & Storyblok: A Hands-on Workshop
Top Content
Featured WorkshopFree
Alba Silvente Fuentes
Roberto Butti
2 authors
This SvelteKit workshop explores the integration of 3rd party services, such as Storyblok, in a SvelteKit project. Participants will learn how to create a SvelteKit project, leverage Svelte components, and connect to external APIs. The workshop covers important concepts including SSR, CSR, static site generation, and deploying the application using adapters. By the end of the workshop, attendees will have a solid understanding of building SvelteKit applications with API integrations and be prepared for deployment.