Advertisement
You need to follow below steps to start using web workers for counting example
1. Create a Web Worker File: You need to write a script to increment the count value. Let's name it as counter.js
1let i = 0;
2
3function timedCount() {
4
5i = i + 1;
6
7postMessage(i);
8
9setTimeout("timedCount()", 500);
10}
11
12timedCount();Here postMessage() method is used to post a message back to the HTML page
2. Create a Web Worker Object: You can create a web worker object by checking for browser support. Let's name this file as web_worker_example.js
1if (typeof w == "undefined") {
2
3w = new Worker("counter.js");
4}and we can receive messages from web worker
1w.onmessage = function (event) {
2
3document.getElementById("message").innerHTML = event.data;
4};3. Terminate a Web Worker:
Web workers will continue to listen for messages (even after the external script is finished) until it is terminated. You can use the terminate() method to terminate listening to the messages.
1w.terminate();4. Reuse the Web Worker: If you set the worker variable to undefined you can reuse the code
1w = undefined;Advertisement
JavaScript Coding Exercise 52
Test your knowledge with this interactive coding challenge.
Start CodingAdvertisement