Web workers are a way of running scripts off the main JS thread. this allows us to run a Turf.js function without stalling the main thread. This allows both the use of loading messages/spinners and for the user to do other things while it's running.
First up, let's look at an example!
I created this example website. It's pre-loaded with 10k points randomly distributes around Australia. Under the map, there are three buttons: Run buffer Synchronously, Run buffer Async, and Clear buffer.
Clicking on the Run buffer Synchronously button will run a Buffer process on the 10k points. This process should take under a second, depending on your computer. Doing this Synchronously stops the user from interacting with the page and stops any animations on the page.
Clicking on the Run buffer Async button will also run a Buffer process on the 10k points. This does take longer to process, almost 3 times on my computer. But it doesn't stop the page from animating or accepting user input.
To make this work, I call a function called
addEventListener in it's own file. The function takes 2 values: the string
"message" and a callback function. The callback function receives an input and posts a message back to where it was called.
For this I import the full TurfJS library, then listen for a message that contains the name of a TurfJS function, and an array containing the function's arguments in order.
To call the Web Worker, I've created a function that handles doing an asynchronous Buffer. It takes the GeoJSON that you want to preform the operation on and a callback function to return the result.
There are 3 things that the function does:
Create the Web Worker
Send the the worker the details is needs to do the operation.
Have the web worker listen for the when the work is finished.
Now, you could make a function that's more generic, but the geospatial inputs for the function are quite different form one function to another and with TypeScript (that I'm using here) that could be a massive headache.
But apart form that, you now have a working implementation for TurfJS in a webworker!