javascriptweb-workerobject-destruction

How to delete Worker object in JavaScript?


In my web app I constantly have to re-instantiate Worker objects, because there is no way of passing new script to old existing objects. After a while, some browsers start blocking creation of new Worker objects, because their limits of Workers for one window is reached. I tried to delete finished worker objects before creating new ones, but apparently I do it in a wrong way. Here is a simple test, which fails in opera (limit is 256 workers per window):

var worker;    
for(var i = 0; i < 300; i++) {
  for (var key in worker) worker[key] = null;
  delete worker.onmessage;
  delete worker.onerror;
  delete worker;
  worker = new Worker("script.js");
}

My question would be how to delete a worker object completely, so that browser limit would never be reached? Thank you!


Solution

  • Not sure if this will work with web worker. Do you create the object on window? If so you can try this:

    delete window.worker
    

    Maybe call terminate and then delete it?

    window.worker.terminate();
    delete window.worker;
    

    The documentation states that it'll stop everything but doesn't clean up when terminate() is called.