如何在Javascript中进行长时间运行的计算时避免冻结浏览器 [英] How to avoid freezing the browser when doing long-running computations in Javascript

查看:104
本文介绍了如何在Javascript中进行长时间运行的计算时避免冻结浏览器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网页,其中函数中的javascript计算需要花费大量时间才能完成并使页面冻结。我应该使用什么技术来确保在后台进行计算时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?

推荐答案

如果您只需要进行计算而不需要在长时间运行计算期间访问DOM,那么您有两个选择:

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. 您可以将计算分解为多个部分,并在 setTimeout()上一次执行一个部分。在每个 setTimeout()调用中,浏览器可以自由地提供其他事件,并使页面保持活动和响应。完成最后一项计算后,您就可以执行结果了。

  2. 您可以在现代浏览器中使用webworker在后台运行计算。当计算在webworker中完成时,它会将消息发送回主线程,然后您可以使用结果更新DOM。

  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.

这是一个相关的答案,也显示了一个例子:在不阻止UI的情况下迭代数组的最佳方法

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

这篇关于如何在Javascript中进行长时间运行的计算时避免冻结浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆