MENU
Dedicated Web Worker
A dedicated Web Worker is a thread spawned from the main JavaScript flow. With dedicated Web Workers you can run on multiple processor cores simultaneously.
A dedicated web worker inherits members from the WorkerGlobalScope, WindowOrWorkerGlobalScope, DedicatedWorkerGlobalScope interfaces, including: console, location, navigator, performance, caches, indexedDB, isSecureContext, origin, atob(), btoa(), fetch(), queueMicrotask(), setInterval(), setTimeout().
The following example tries to find prime numbers fast by running the computation (not the most efficient algorithm!) in parallel threads.
RESETRUNFULL
RESETRUNFULL
// /shared/prime.js (fixed)
onmessage = ev=>{
n = ev.data;
var isPrime=true;
if (n>2)
for (i=2; i<Math.sqrt(n)+1; i++)
if (n%i==0){isPrime=false; break;}
postMessage({n,isPrime});
}
<!DOCTYPE html><html><body>
<p>Prime numbers: <output></output></p>
<button onclick="startWorker()">Start a Worker</button>
<button onclick="workers.pop().terminate();">Stop a Worker</button>
<script>
var c=0;
var last = 2;
var workers =[];
var startTS=Date.now();
function startWorker() {
if(!Worker) {
document.querySelector("p").innerHTML=
"Your browser does not support Web Workers...";
}
var w = new Worker("/shared/prime.js");
w.onmessage = function (e) {
if (last==2) last++;
else last+=2;
if (last>1000000){
workers.forEach(wk=>wk.terminate());
document.querySelector("p").innerHTML=
`${Math.round((Date.now()-startTS)/1000)}s taken by ${workers.length} workers to get ${c} prime numbers.`;
}
if (e.data.isPrime){
c++;
if (c%1000==0) document.querySelector("output").innerHTML = e.data.n;
}
w.postMessage(last);
}
workers.push(w);
w.postMessage(last);
}
</script>
</body></html>
You can import one or more scripts into the worker's scope:
importScripts('foo.js', 'bar.js');
The navigator.hardwareConcurrency read-only property returns the number of logical processor threads available to run software threads on the user's computer.