I try to access web workers when I encounter very complex behavior. For some reason, it stopped after a few seconds, although I have a code in it that works.
Here is my code;
Main JavaScript file:
$(document).ready(function () { var worker = new Worker("js/TestWorker.js"); worker.addEventListener('message', function (event) { console.log(event.data); }); worker.addEventListener('error', function (event) { console.log(event); }); });
Working file:
(function () { var updateCounter = 0; var updater = function () { updateCounter += 1; console.log("Update counter: " + updateCounter); postMessage("test"); setTimeout(updater, 10000); }; updater(); })();
As indicated, the employee simply ceases to function after a few seconds, 10-20 seconds or so.
But if I add this piece of code to my main JavaScript file,
var check = function () { var localWorker = worker;
The employee works as intended. SetTimeout calls are also not required, so they are commented out. (Note that I can simply replace the destination with a working .length or something similar, and it will still work fine.
Can someone explain this behavior? Does the working and (erroneously) garbage collected by the browser end up, or is something else happening here that I am missing?
It should be noted that my browser (Chrome) does not display any errors or warnings on the console.
EDIT: The same behavior is observed, regardless of whether the code is executed inside an anonymous function or not.
EDIT2: If I put a working variable in the global scope, it does not end prematurely. What could be the reason for this?