HTML5 Game - Use webworker to do multithread in browser

Introduction

HTML5 has a new technology called the Web worker.

Here's essentially how to use a Web worker:

  • Create your page and JavaScript code as usual.
  • Move the javascript that's hogging the CPU to a separate .js file.
  • This new .js file will hold a function or several functions of code that will run from running in a separate thread.
  • In your main page, create a Worker object.
  • The new object expects the name of a .js file as its single parameter.
  • The browser will create a Web worker based on that file.
  • Create a function to run when you receive a message from the worker.
  • Web workers use a message-passing algorithm. The worker and the main page are entirely different programs to the CPU. The only way they communicate is by passing messages back and forth.
  • The worker object has an onmessage event handler. Attach a function to this message, and the function will activate every time the main program receives a message from the worker.
  • The worker object has a postMessage() method. Send a value to this message, and that message will be sent to the worker.
  • Destroy the Worker object when you're finished.

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");
  }
}

Related Topics