Avoiding the “script is running too long” dialog,

2019-06-06 17:34发布

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?

3条回答
Summer. ? 凉城
2楼-- · 2019-06-06 17:49

Javascript is single threaded, so that's the main obstacle.

If you want to perform a lot of calculations, preferably you should use Workers, however those are only supported by modern browsers. This so that your calculations don't slow down the UI, which should be in the main thread. This is a common practice when building desktop apps.

Splitting the calculation might be a good idea if you don't mind it taking a lot longer than it should. That should prevent the popup from appearing, provided you time it right.

You should also perhaps reconsider the need of performing so many calculations on the client side.

查看更多
该账号已被封号
3楼-- · 2019-06-06 17:55

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.

查看更多
Luminary・发光体
4楼-- · 2019-06-06 17:56

You could use this: multithreading. it's not really multithreading, it's just playing with timers. It will prevent the popup. But I am not sure if it is necessary in this case, unless you're making a full-on game.

查看更多
登录 后发表回答