joseph oun
joseph oun

Reputation: 135

Writing threads in JavaScript

Can we achieve multi-threading in JavaScript?

If yes, please suggest a method to run multiple tasks on multiple threads in JavaScript/Angular.

Thanks

Upvotes: 3

Views: 1617

Answers (2)

Tushar Acharekar
Tushar Acharekar

Reputation: 900

Using Web worker you can achieve multithreading in addition use can use service-worker that will acts like your proxy-server, with that you can achive multithreading at network level.

Things to note about a service worker:

  • It's a JavaScript Worker, so it can't access the DOM directly. Instead, a service worker can communicate with the pages it controls by responding to messages sent via the postMessage interface, and those pages can manipulate the DOM if needed.
  • Service worker is a programmable network proxy, allowing you to control how network requests from your page are handled.
  • It's terminated when not in use, and restarted when it's next needed, so you cannot rely on global state within a service worker's onfetch and onmessage handlers. If there is information that you need to persist and reuse across restarts, service workers do have access to the IndexedDB API.
  • Service workers make extensive use of promises, so if you're new to promises, then you should stop reading this and check out Promises, an introduction.

Upvotes: 1

Jose Paredes
Jose Paredes

Reputation: 4080

You could use Web worker, a dedicated thread that doesn't block the UI. They work in a background thread

Web Workers is a simple means for web content to run scripts in background threads. The worker thread can perform tasks without interfering with the user interface. In addition, they can perform I/O using XMLHttpRequest (although the responseXML and channel attributes are always null). Once created, a worker can send messages to the JavaScript code that created it by posting messages to an event handler specified by that code (and vice versa.) This article provides a detailed introduction to using web workers.

mainThread.js

if (window.Worker) {
  var myWorker = new Worker('worker.js');

  // Posting data to worker
  myWorker.postMessage('Message posted to worker');

  // Receiving data from worker
  myWorker.onmessage = function(e) {
    console.log('Message received from worker: ' + e.data);
  }
}

worker.js

onmessage = function(e) {
  // Receiving data from main thread
  console.log('Message received from main script: ' + e.data);

  // Posting data to the main thread
  postMessage('Posting message back to main script');
}

For further information read the documentation in MDN Web Workers

Upvotes: 7

Related Questions