Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
135
rated 0 times [  141] [ 6]  / answers: 1 / hits: 38479  / 12 Years ago, sat, november 24, 2012, 12:00:00

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?


More From » performance

 Answers
23

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


[#81819] Friday, November 23, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
irvingcarloe

Total Points: 677
Total Questions: 109
Total Answers: 96

Location: Svalbard and Jan Mayen
Member since Sun, Sep 25, 2022
2 Years ago
;