Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptMutlithreading in JavaScript

Mutlithreading in JavaScript

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 neveropen");
}, 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 neveropen

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments