Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a web page where a javascript calculation in a function takes lot of time to finish and makes the page to freeze. What technique should I use to make sure the javascript does not freeze the browser when the calculation is happening in the background?

like image 863
Ravi Avatar asked Nov 24 '12 22:11

Ravi


1 Answers

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

like image 50
jfriend00 Avatar answered Sep 25 '22 17:09

jfriend00