


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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...
