Refs
- WSchools Web Workers
What and why
- Web workers enable web content to run scripts in background threads, without interfering with user interface.
- Web workers support: TODO
Example
Simple counter
1 2 3
| simple-counter - index.html - demo-worker.js
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| <!DOCTYPE html> <html> <body>
<p>Count numbers: <output id="result"></output></p> <button onclick="startWorker()">Start Worker</button> <button onclick="stopWorker()">Stop Worker</button>
<p><strong>Note:</strong> Internet Explorer 9 and earlier versions do not support Web Workers.</p>
<script> var 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>
|
1 2 3 4 5 6 7 8 9 10
| var i=0;
function timedCount() { i=i+1; postMessage(i); setTimeout("timedCount()", 500); }
timedCount();
|
Use serve
to host the page. Web worker does not work by just double click the index.html
file.