Time for action – Mandelbrot using a web worker
Now we will implement the same thing except this time we will use a web worker to offload the processing onto another thread. This will free up the main thread to handle page updates and user interaction. You can find the source code for this section in Chapter 9/example9.3
.
Let's go into the HTML and add a checkbox where we can select whether to use web workers or not. This will make it easier to compare results in the browser:
<input type="checkbox" id="use-worker" checked /> <label for="use-worker">Use web worker</label>
We'll also add a stop button. There was no way to stop before without web workers because the UI was locked up, but now we will be able to implement it:
<button id="stop">Stop Drawing</button>
Now let's go ahead and create our web worker in a new file named mandelbrotWorker.js
. Our worker needs to use the MandelbrotGenerator
object so...