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

后端 未结 5 1929
慢半拍i
慢半拍i 2020-11-28 09:15

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 javascr

5条回答
  •  执念已碎
    2020-11-28 10:02

    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

提交回复
热议问题