HTML5 has a new technology called the Web worker.
Here's essentially how to use a Web worker:
The main page is as follows:
<!DOCTYPE HTML> <html lang = "en"> <head> <script type = "text/javascript"> let worker; let output; function startWorker(){ //initialize worker worker = new Worker("worker.js"); output = document.getElementById("output"); //when we get a message from worker, run update function worker.onmessage = update; //tell worker to get started worker.postMessage("start"); } function update(evt){ //update the page with current message from worker output.innerHTML = evt.data; } function stopWorker(){ //stop the worker worker.terminate(); } </script> </head> <body> <h1>Web worker demo</h1> <button onclick = "startWorker()" type = "button"> start web worker </button> <button type = "button" onclick = "stopWorker()"> stop web worker </button> <div id = "output"> default output </div> </body> </html>
File:worker.js
//tell system to runloop when a message comes in onmessage = runLoop; function runLoop(evt){ if ( evt.data === "start" ) { for(i = 0; i < 100000; i++){ postMessage(i); } //send a message showing we're done postMessage("finished"); } }