Search code examples
javascriptweb-worker

Stopping a webworker whilst its processing a large amount of data?


I am wanting to use Web Workers to process image data in chunks and apply filters to the image data as working directly on the UI thread appears to be slow. (My question is not specific to image data processing in the grand scheme of things)

The main issue whilst I am coming up solutions to my issue is that if I was to split the image I am processing into chunks and then send that data to the Web Workers I would still like to be able to cancel the processing by sending another message to the web workers. It is my assumption though if I use a traditional loop (and not a recursive function that yields) to process the data that I will not be able to receive further messages until that process is completed (negating the usefulness of sending a cancel message).

Is this the case? I have not tried it as of yet but I would like to know if its worthwhile for me to somehow split this data further in the web worker itself so it can continue to receive further messages and process them.

If splitting it up is the best method, how would you go about essentially yielding? I assume it would be some sort of 1 millisecond timeout which then allows the event loop to process the incoming messages and then have my process function pick up where it left off, but if this isnt the way to do this, could someone suggest another?


Solution

  • You can use your main web-worker to spawn subworkers rather than "yeilding" ... so let the main web-worker you spawn for image processing handle both incoming messages from the main UI thread, as well as create chunks of data for image-processing tasks that it issues to it's own subworkers. That way you can easily terminate or manage any child-workers depending on what messages come in from the main UI thread, and your main web-worker remains responsive at all times without blocking, needing to have some form of a "yield", or wait for some fixed timeout period before it can respond to messages again.