Web page stuck while the web worker faced an endless loop

Viewed 35

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?

1 Answers

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.

Related