Bill Yan
Bill Yan

Reputation: 3468

does a webworker close itself after its code finishes?

if I let a webworker run a function. will it close itself after the function is finished?

(function(){a = 3+2;})();

or I will need to explicitly close this webworker by calling webworker's close() function?

Upvotes: 2

Views: 1509

Answers (2)

4esn0k
4esn0k

Reputation: 10407

Quick test: It will create 1000 workers, please check the memory usage after some time.

function doAThing(i) {
  var myWorker = new Worker("data:application/javascript," + encodeURIComponent("onmessage = function(e) { postMessage(3 + 2); }"));
  myWorker.postMessage(1);
  myWorker.onmessage = function(e) {
    console.log('Message received from worker ' + i, e.data);
    myWorker.onmessage = null;
    if (document.querySelector('#terminate').checked) {
      myWorker.terminate();
    }
  };
}
function run() {
  for (let i = 0; i < 1000; i++) {
    setTimeout(() => doAThing(i), 50);
  }
}
<div>
  <input type="radio" id="terminate" name="terminate" value="yes" />
  <label for="terminate">Terminate</label>
</div>

<div>
  <input type="radio" id="donotterminate" name="terminate" value="no" />
  <label for="donotterminate">do not terminate</label>
</div>
<button onclick="run()">Run</button>

Upvotes: -1

Michael Powers
Michael Powers

Reputation: 2050

You don't need to call close() or terminate() on web workers. Web workers automatically clean themselves up when they fall out of scope like most JavaScript objects. So in your example, if your web worker looked like this:

onmessage = function(e) {
    postMessage(3 + 2);
}

And you called it from your main script like this:

function doAThing() {
    var myWorker = new Worker('worker.js');
    myWorker.postMessage();
    myWorker.onmessage = function(e) {
        console.log('Message received from worker', e.data);
    };
}

The worker would cease execution after it posted back the result of 3 + 2, but would still be in memory and could still be called until the myWorker variable fell out of scope.

In this example case you'd no longer be able to call the worker after doAThing() completed, and the garbage collector should clean up the worker after doAThing() completes and the message callback gets called, since at that point nothing will have a reference anymore.

The case where you'd want to call close() or terminate() is if you have a long living task you want to end early (say you want to end an XHR request early, or if a user hits a "Cancel" button).

Upvotes: 2

Related Questions