HTML Web Workers

You are Here:

HTML Web Workers

The HTML Web Workers is a JavaScript executed from an HTML page that runs in the background, independently without affecting the performance of the page.

Purpose of Web Workers

The HTML Web Workers is useful in performing a computationally expensive task without interrupting the user interface.

Note: Web workers are often able to utilize multi-core CPUs more effectively.

Example

The following is your web-worker.js file. In the below code postMessage() method is used to post a message back to the HTML page.

web-worker.js
var i = 60; function timerClock() { i = i - 1; postMessage(i); if(i>0){ setTimeout("timerClock()", 1000); } } timerClock();
HTML Online Editor
<!DOCTYPE html> <html> <body> <p>Timer: You Have <output id="point">59</output> sec</p> <button onclick="startWorker()">Start Worker</button> <button onclick="stopWorker()">Stop Worker</button> <script> var w; var x = document.getElementById("point"); function startWorker(){ if(typeof(Worker) !== "undefined"){ if(typeof(w) == "undefined"){ w = new Worker("/web-workers.js"); } w.onmessage = function(event){ x.innerHTML = event.data; }; } else{ x.innerHTML = "Sorry, your browser does not support Web Workers"; } } function stopWorker(){ w.terminate(); w = undefined; } </script> </body> </html>

Reminder

Hi Developers, we almost covered 99.5% of HTML Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in HTML.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author