Open In App

Mutlithreading in JavaScript

Last Updated : 29 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Multithreading is the ability of any program to execute multiple threads simultaneously. As we know JavaScript is a single-threaded programming language, which means it has a single thread that handles all the execution sequentially. Single-threaded means one line of code run at once. Originally, Javascript is single-threaded because it was just used in web browser scripting language for a single user but nowadays it evolve into something bigger and make the computation very huge.

There are various techniques to stimulate multithreading in JavaScript:

Web Workers

Web Workers are giving us the possibility to write multi-threaded JavaScript, which does not block the DOM. Even the Asynchronous operations block the DOM to some extent. On the other side, web workers help us to solve this problem, escaping the single-threaded environment and reaching a higher performance of our web pages. Basically, web workers run the script in the background thread and which avoids the interference in user interface. Due to the feature of a background thread, we can create or run a costly operation.

Example 1: In this example, we will show what is the difference in the behavior of our page with and without workers.

  • main.js

Javascript




// Creating new web worker
const worker = new Worker('worker.js');
let message = 'Hello';
  
// Message using postMessage
worker.postMessage(message);
  
// Response
worker.onmessage = function (e) {
    console.log(e.data);
};


  • worker.js

Javascript




self.onmessage = function (e) {
    if (e.data !== undefined) {
        let total = e.data + 'Geeks';
        self.postMessage(total)
    }
}


Output:

'Hello Geeks'

Explanation: In this example, we have created two JavaScript files: main.js and worker.js. main.js represent the main file and worker.js represent the worker file. In the example above, the worker is doing the work of concatenating the received string with the defined one and sending it back to the main.js file without interrupting the page.

Asynchronous Programming

Asynchronous calls the next statement gets executed without even waiting for the previous one’s execution. JavaScript provides us with callbacks, promises, and async/await for executing a non-blocking function. Through Asynchronous programming, we achieve a parallel-like behavior by initiating multithreading and also handling its completion.

Example 2: In this example, we are using the setTimeout() function for Asynchronous Programme to illustrate Multithreading in Javascript.

Javascript




console.log("Starting...");
setTimeout(function () {
    console.log("Welcome to geeksforgeeks");
}, 2000);
console.log("Ending...");


Output: The above example shows that when we use an asynchronous program, the code doesn’t block in fact it executes the next line and the function executes after a specified time.

Starting...
Ending...
Welcome to geeksforgeeks


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads