search
HomeWeb Front-endJS TutorialUtilize Multi-Thread in Javascript - Not About WebWorkers nor WebAssembly

Utilize Multi-Thread in Javascript - Not About WebWorkers nor WebAssembly

It's well known that JavaScript runs on a single thread. This concept is so integral that we often refer to it by name - the Main Thread. So, does that mean your multi-core CPU is useless when running JavaScript?

Not quite.

JavaScript can be a bit cheeky, sending mixed messages about its threads.

But even without delving into more complex features like Web Workers and WebAssembly, basic JavaScript can utilize multi-threaded workflows.

To be clear, this article focuses on web browser-based JavaScript. Other environments, like Node.js, may handle things differently.

We're going to explore options for multi-thread and multi-thread-like operations in JavaScript. The reality is - you can and should utilize multi-threaded workflows in basic, pure vanilla JavaScript.

"Explain!"

Happy to.

JavaScript is a single-threaded language, but it's interpreted by web browsers - and browsers are multi-threaded software.

There are several methods to simulate and utilize multi-threading, and you might be using them without even realizing it.

Additionally, JavaScript often behaves in ways that seem multi-threaded without actually being so. It might sound like cheating, but it effectively delivers the benefits we expect from multi-threaded behavior.

Event-Based Programming Feels Multi-Threaded

JavaScript is an event-based system. When the browser processes a JavaScript file, it runs all the code inside. It's entirely possible to write code that doesn't stop running - though that's generally a bad idea because it can crash the browser.

What we usually do is set up event listeners and wait for something to happen. At this point, JavaScript is completely idle. This idle waiting wouldn't be possible without offloading some work from the Main Thread.

Events themselves aren't multi-threaded, but the waiting and checking for events is handled by the browser, not by JavaScript. This process is offloaded from the Main Thread.

Asynchronous Functions and Multi-Threading

Functions like setTimeout and setInterval have been with us for many years. They offload the waiting time from the Main Thread.

Let's simplify how this works. In lower-level languages, timers and waiting are often implemented by constantly checking, "Is it time already?" Imagine a while() loop that checks the elapsed time and proceeds when the time is right. Modern approaches might use CPU interrupts to avoid clogging the CPU thread.

However, when you use setTimeout or setInterval in JavaScript, the language is completely idle during the wait, which, again, means the waiting is processed somehow out the Main Thread.

Fetch and Other Asynchronous APIs

These days, we're getting more and more asynchronous functions and APIs from browsers. The fetch API is a well-known example. Even newer APIs, like the Clipboard API, are asynchronous.

This means you ask the browser to perform an action, and it frees up JavaScript's Main Thread (or allows it to process other stuff - more on that later) and notifies you (by processing the following code) when it's done.

Asynchronous vs. Multi-Threaded

Asynchronous doesn't necessarily mean multi-threaded - not always, not directly. Simply putting the word async in front of a function doesn't do a shit for you.

There are two key components to how JavaScript handles asynchronous behaviors:

1. Callback Queue and Event Loop

Think of the callback queue as a line of functions waiting to run. These functions execute one by one in the Main Thread. When an asynchronous operation completes - be it an event, a timeout, or a completed fetch - its callback is placed in this queue.

The event loop is responsible for moving callbacks from the queue to the call stack when the call stack is empty.

2. Browser-Processed Functions

The web browser takes control of certain operations and may spin up new threads for them—this includes actions like fetch or setTimeout. JavaScript doesn't need to manage these threads. When the asynchronous operation is complete, the browser places the corresponding callback into the callback queue, and JavaScript continues execution from there.

Consider this code:

console.log('Start');

setTimeout(() => {
  console.log('This is asynchronous');
});

console.log('End');

Output:

Start
End
This is asynchronous

Here's what happens:

  • 'Start' is logged.
  • setTimeout is called without a timeout parameter, so it defaults to 0 milliseconds. The callback is sent to the browser to execute after the current call stack is clear.
  • 'End' is logged.
  • The Main Thread is now free, and the event loop checks the callback queue.
  • The callback function from setTimeout is moved to the call stack.
  • 'This is asynchronous' is logged.

Notice that setTimeout is missing the timeout parameter. This is a common technique to defer lower-priority code execution - first process all else, after that’s done, do the “lower priority” thing.

What this does is place the function inside setTimeout into the callback queue immediately, and it runs at the first opportunity when the Main Thread is idle.

The Special Case of requestAnimationFrame

requestAnimationFrame is a browser API that tells the browser you want to execute some code just before it calculates and updates the view (think of it as frames per second in video games).

For some reason, web developers do not think in repaints and FPS, but that’s how it works.

It's inherently asynchronous (though not multithreaded).

Using setTimeout without a specified time was often used for similar purposes before requestAnimationFrame was introduced, though it was far from being as useful (just better than nothing).

This function queues your code into a special stack. Just before rendering a new frame (the repaint), the browser runs this queued code. It's perfect for making changes to the DOM, HTML, or CSS (and only those, please, I forbid you making calculations there!).

True Multi-Threading Options

While this article isn't about them, it's worth mentioning that you can achieve true(er) multi-threaded operations by utilizing Web Workers and WebAssembly. These allow you to run scripts in background threads. They cannot directly manipulate the DOM, but they're invaluable for processing heavy tasks (matrix calculations, anyone?). This approach is often used in HTML5-based games - the more complex ones, not just tic-tac-toe.

Last Words

JavaScript, when isolated, remains single-threaded. But in the real world, it's an interpreted language running within multi-threaded environments of web browsers. If your interpreter offers you a helping hand, take it and use it.

This article covers a lot - basic knowledge, low-level explanations, and more. But that's often how development is - all interconnected. That's why I like to look at the broader picture; sometimes, a detailed focus isn't the solution to a problem.


Has async ever caused you debugging nightmares?
I certainly have - some years ago, getting stacks with errors wasn’t much of a thing.

The above is the detailed content of Utilize Multi-Thread in Javascript - Not About WebWorkers nor WebAssembly. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.