The following lines check if the web worker already exists.
If it doesn’t, they create a new web worker object and execute the code from “demo_workers.js”:
if (typeof(w) == “undefined”) { w = new Worker(“demo_workers.js”); } |
Next, add an “onmessage” event listener to the web worker to handle messages sent and received from it.
w.onmessage = function(event){ document.getElementById(“result”).innerHTML = event.data; }; |
When the web worker sends a message, the code inside the event listener is triggered. The data from the web worker is accessible via event.data
.
Once a web worker object is created, it remains active and continues to listen for messages, even after the external script has finished execution.
To stop a web worker and release browser and computer resources, use the terminate() method:
w.terminate(); |
Once you terminate a web worker using the terminate() method, you can set the worker variable to undefined and reuse the code.
w = undefined; |
We’ve already reviewed the code for the Worker in the .js file. Below is the code for the HTML page:
<!DOCTYPE html> <html> <body> <p>Count numbers: <output id=”result”></output></p> <button onclick=”startWorker()”>Start Worker</button> <button onclick=”stopWorker()”>Stop Worker</button> <script> var w; function startWorker() { function stopWorker() { </body> </html> |
Because web workers operate in external files, they do not have access to the following JavaScript objects: