Aryan PrajapatKnowledge Contributor
Give an example of a web worker in js?
Give an example of a web worker in js?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Questions | Answers | Discussions | Knowledge sharing | Communities & more.
You need to follow below steps to start using web workers for counting example
Create a Web Worker File: You need to write a script to increment the count value. Let’s name it as counter.js
let i = 0;
function timedCount() {
i = i + 1;
postMessage(i);
setTimeout(“timedCount()”, 500);
}
timedCount();
Here postMessage() method is used to post a message back to the HTML page
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
if (typeof w == “undefined”) {
w = new Worker(“counter.js”);
}
and we can receive messages from web worker
w.onmessage = function (event) {
document.getElementById(“message”).innerHTML = event.data;
};
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.
w.terminate();
Reuse the Web Worker: If you set the worker variable to undefined you can reuse the code
w = undefined;