Home > Web Front-end > JS Tutorial > Utilize Multi-Thread in Javascript - Not About WebWorkers nor WebAssembly

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

Mary-Kate Olsen
Release: 2024-12-06 04:11:22
Original
262 people have browsed it

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');
Copy after login

Output:

Start
End
This is asynchronous
Copy after login

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!

source:dev.to
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template