3

I am working on a web project that needs quite a few calculations, and I use a web worker to do so. There is also a button on the web page that should terminate the worker's calculation whenever the user clicked it. However, when I wrote an endless loop inside the web worker to test, the webpage stuck and I cannot interact with it.

//When the worker is created
worker = new Worker("./scripts/testWorker.js");

//When the button is clicked
worker.terminate();
worker = undefined;

How to solve this problem? Or are there any other ways to reach the goal of performing breakable calculations?

  • See if the [this linked answer](https://stackoverflow.com/a/46371746/2055998) is relevant to you. – PM 77-1 Sep 13 '22 at 16:59
  • I solved this problem. The problem is that my infinite loop contains a postMessage function. And it post too much messages to the main thread that the main thread stuck. – Lazenander Yang Sep 16 '22 at 09:23
  • Glad to hear. You may want to post your own answer and accept it afterwards, if you feel that it can help others in a similar situation. – PM 77-1 Sep 16 '22 at 15:20

1 Answers1

1

In the endless loop of the worker thread, there is a postMessage function. Hence, the onmessage function in the main thread is called rapidly. Therefore, the main thread stuck when the worker starts. Deleting this postMessage inside the endless loop of the worker thread solved this problem.