Question about canceling a web worker

Question about canceling a web worker

I've seen this question asked before (specifically this most recent thread) but I can't seem to implement a sufficient solution.

My usage model is that I have many buttons that will update a single chart. When any button is clicked, a SQL query is launched. If many buttons are clicked, I would like to cancel all previous queries, and only return the data for the very last button clicked.

I've seen examples of using .terminate() externally, and .close() internally. terminate() seems to be reasonable, but I think I am using it wrong (I'm pretty new to JS). I think the issue I'm having has to do with scoping, but I have no clue how to do this correctly. I'm probably constructing the web worker badly. The result is that everything is completely serialized, so I can click 10 buttons, and I end up with 10 iterations of the data loading. The goal is to have the chart load only once, with the data returned from the very last query launched. Any advice would be VERY appreciated!

var getdata = function(someparameters) {

var myWorker = new Worker("worker.js"); if (window.Worker) { return new Promise(function(resolve){ myWorker.terminate(); resolve(true); }).then(function() { var message = {params : someparameter}; var myWorker = new Worker("worker.js"); myWorker.postMessage(message); myWorker.onmessage = function(e) { updateSomething(JSON.parse(; }; }); 


Editing for formatting.. not sure why the first/last lines of code aren't in the box 🙂

Submitted August 12, 2017 at 07:21AM by coldcoffeecup
via reddit


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s