How to avoid freezing the browser when doing long-running computations in Javascript

If you only need to do a calculation and don’t need to access the DOM during the long running calculation, then you have two options:

  1. You can break the calculation up into pieces and do a piece at a time on a setTimeout(). On each setTimeout() call, the browser will be free to serve other events and will keep the page alive and responive. When you finish the last piece of the calculation, you can then carry out the result.
  2. You can run the calculation in the background using a webworker in modern browsers. When the calcuation is done in the webworker, it sends a message back to the main thread and you can then update the DOM with the result.

Here’s a related answer that also shows an example: Best way to iterate over an array without blocking the UI

Leave a Comment