I am writing a javascript program with a very long-running foreach loop like the following:
for (property in object) {
difficultTask();
}
I've seen that you can do some things with setTimeout
which can allow you to periodically return control to the browser; however, I haven't seen any that are able to do this with a foreach loop, only a for loop with an index. Additionally, these tasks cannot be completed asynchronously since each iteration depends on a result from the previous iteration.
One solution I can think of is to split up my object into a lot of smaller objects and iterate through each of them, setting a timeout in between each one, but I'd like to see if this is possible without resorting to that.
Is there a way to do this without drastically changing how I have my objects?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…