Stopping workers with terminate
Not all problems are cumulative. Some have a desired goal state; once it is found, then the program can exit. We've seen that workers communicate their results by posting messages. Now our program is completed, it would be nice to prevent future messages from being received, possibly polluting our results.
In this recipe, we'll see how to use Worker.terminate
to immediately stop a Worker
.
Getting ready
This recipe assumes you already have a workspace that allows you to create and run ES modules in your browser. If you don't, please see the first two chapters.
How to do it...
- Open your command-line application and navigate to your workspace.
- Create a new folder named
05-04-stop-workers-with-terminate
. - Copy or create an
index.html
that loads and runs amain
function frommain.js
.
- Create a
main.js
with a function namedonMessage
that takes amessage
andworkers
argument, logs out thetype
andtimeout
properties ofmessage.data
, and callsterminate
on all theworkers
...