This site is mobile accessible. Press the "Tap Here" button to use a different font-size.
Smartphone icons created by Freepik - Flaticon
A web worker is a JavaScript running in the background, without affecting the performance of the page.
The numbers in the table specify the first browser versions that fully support Web Workers:
Chrome 4 | IE 10 | Firefox 3.5 | Safari 4 | Opera 11.5 |
Jan 2010 | Sep 2012 | Jun 2009 | Jun 2009 | Jun 2011 |
The example below creates a simple web worker that count numbers in the background:
Before creating a web worker, check whether the user's browser supports it:
if (typeof(Worker) !== "undefined") {
// Yes! Web worker support!
// Some code.....
} else {
// Sorry! No Web Worker support..
}
let i = 0;
function timedCount() {
i ++;
postMessage(i);
setTimeout("timedCount()",500);
}
timedCount();
if (typeof(w) == "undefined") {
w = new Worker("demo_workers.js");
}
w.onmessage = function(event){
document.getElementById("result").innerHTML = event.data;
};
When the web worker posts a message, the code within the event listener is executed. The data from the web worker is stored in event.data.
w.terminate();
If you set the worker variable to undefined, after it has been terminated, you can reuse the code:
w = undefined;
We have already seen the Worker code 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> let w; function startWorker() { if (typeof(w) == "undefined") { w = new Worker("demo_workers.js"); } w.onmessage = function(event) { document.getElementById("result").innerHTML = event.data; }; } function stopWorker() { w.terminate(); w = undefined; } </script> </body> </html>
Eventually the navigation links, above, will be replaced by these (previous) and (next) buttons below.
JavaScript icons used in the buttons provided by ICONS8.COM. Smartphone icons created by Freepik - Flaticon