I have a javascript loop that takes some time to process. I wish I could slim it down but it has to process a large amount of data. While it's running the browser becomes unresponsive of course. I've read the best way to handle this in javascript is using an asynchronous loop of some sort. This way mouse clicks, etc, can continue to be processed in between loop processing. Is there any standard async frameworks that will work well for this? Or can someone provide a simple example of how this might be coded? Thanks!
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
You can simply wrap each iteration of the loop in a
setTimeout
like so (see jsfiddle):Simply break the work up in to chunks and process one chunk at a time. The code here is a good starting place, but use
setImmediate
orsetTimeout
to call the next iteration of the loop.The proper way to solve your problem is to use Web Workers, which execute code on a separate thread.
Sadly WebWorkers are not available yet on everyone's browser. I have been using the "setTimeout(Func,0);" trick for about year. Here is some recent research i wrote up to explain how to speed it up a bit. If you just want the answer, skip to Step 4. Step 1 2 and 3 explain the reasoning and mechanics;