'Is there a way to pause and restart the webworker?

I have a problem with my webworker and hope that somebody can help me.. I have a browser side with two buttons - one starts my worker (numbers are getting incremented), the other one pauses the worker. If I click on the start button again, it should continue where it was interruptet. In my javascript file I call the webworker based on the button click:

buttonClick: function () {
        if (typeof (this.w) == "undefined") {
            this.w = new Worker("theWorker.js");
            this.w.onmessage = this.workerResponse;
            this.w.postMessage("start");
        }
    }

My worker:

onmessage = function(e) {
    if(e.data=="start"){
    run();
  }
}

function run(){
while(true){
    // numbers are getting incremented
}

My question is - how can I pause the worker? I don't want to terminate it, because then everything gets reseted, but I want to start again with the current number. I hope, anybody can help! If there is too less information, I can edit my post. Thanks!



Solution 1:[1]

Considering you are targeting latest browser, with access to SharedArrayBuffer and Atomics. Simplest solution is to pass SAB reference to the worker:

main.js

const sab = new SharedArrayBuffer(4);
const int32 = new Int32Array(sab);

buttonClick: function () {
        if (typeof (this.w) == "undefined") {
            this.w = new Worker("theWorker.js");
            this.w.onmessage = this.workerResponse;
            this.w.postMessage({kind:"start", sab});
        }
    }

pause: function() {
    Atomics.store(int32, 0, 1);
    Atomics.notify(int32, 0);
}

resume: function() {
    Atomics.store(int32, 0, 0);
    Atomics.notify(int32, 0);
}

...worker loop will wait for the byte to have particular value 1/0.

worker.js

let int32;
onmessage = function(e) {
    if(e.data.kind=="start"){
        int32 = new Int32Array(e.data.sab);
        run();
    }
}

function run(){
    while(true){
        Atomics.wait(int32, 0, 1);
        // numbers are getting incremented
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yoz