Can we achieve multi-threading in JavaScript?
If yes, please suggest a method to run multiple tasks on multiple threads in JavaScript/Angular.
Thanks
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
Using
Web workeryou can achieve multithreading in addition use can useservice-workerthat will acts like your proxy-server, with that you can achive multithreading at network level.
Things to note about a service worker:
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With