避免“脚本运行时间过长".对话框中,我应该拆分功能并定期运行它吗? [英] Avoiding the "script is running too long" dialog, should I split up my function and run it at intervals?

查看:57
本文介绍了避免“脚本运行时间过长".对话框中,我应该拆分功能并定期运行它吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的JavasScript for loop在我的页面之一上运行. 太大了,它导致旧版本的IE弹出窗口显示如下内容:此页面的脚本使其运行缓慢,您要终止它吗?"

我相信我已经尽可能地优化了它,所以现在我正在寻找替代方法.

我想知道创建一个运行前100次迭代,然后运行第二100次迭代,然后运行第三次,直到所有迭代都完成的间隔对我是否有益?这样是否可以防止IE弹出窗口声称脚本运行太慢?

解决方案

只要您的代码没有足够快地将控制权返回给浏览器的主事件处理循环,就会出现脚本过长"的浏览器弹出窗口. >

按照问题中的建议使用setTimeout来批量触发计算,确实会阻止弹出窗口的出现.

定期返回事件循环还可以使浏览器保持对其他UI事件的响应-您可以(例如)提供一个取消"按钮.我建议您尝试至少每秒产生一次,即使不是那么频繁.

I have a very large JavasScript for loop running on one of my pages. It is so large that it is causing an IE popup in old versions that says something like: 'A script of this page is making it run slow, do you want to terminate it?'

I'm confident that I have optimized it as much as possible so now i'm looking for alternate ways to do it.

I'm wondering whether it would be beneficial for me to create an interval that ran the first 100 iterations, then the second 100 iterations, then the third and so on until all the iterations were complete? Would this prevent the IE popup claiming that the scripts are running too slow?

解决方案

The "script too long" browser popup will appear any time that your code doesn't yield control back to the browser's main event processing loop quickly enough.

Using setTimeout as you suggest in the question to trigger your calculations in batches would indeed prevent the popup from appearing.

Yielding back to the event loop periodically will also allow the browser to remain responsive to other UI events - you could (for example) offer a "cancel" button. I would suggest that you try to yield at least once a second, if not somewhat more frequently than that.

这篇关于避免“脚本运行时间过长".对话框中,我应该拆分功能并定期运行它吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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