I have a main thread, which contains a handleSubmit
:
function handleSubmit({ ref }) { // ref is a react useRef
const worker = new Worker('Workers/SolveWorker.js');
worker.postMessage(ref);
I also have a handleCancel
, which mutates my useRef:
function handleCancel() {
allowedToRunRef.current = false;
}
Inside my worker:
onmessage = function (e) {
const startTime = Date.now();
while (Date.now() < startTime + 5000 && e.data.allowedToRunRef.current) {
// do nothing
}
postMessage(finalSolutions);
};
My idea is that when I submit my query, it starts a computation inside a webworker thread. If a user wants to cancel the computation, they can do so, mutating the flag, which kills the while loop inside the worker.
However, this does not work, as you cannot pass things by reference to web workers, it seems.
How can I fix the problem of allowing for a shared flag, to allow for premature cancellation?