问题描述
之前我曾经问过这个问题,并且在网上找到了一些关于这个主题的文章,但对于我的生活,我无法弄清楚这一点。我有一组计算模型的Javascript函数,但是有大量的循环使脚本需要一段时间(~4秒)。我不介意处理时间,但IE提示警告,因为有太多的执行。
I've asked about this before, and have found a few articles online regarding this subject, but for the life of me I cannot figure this out. I have a set of Javascript functions that calculate a model, but there's a ton of looping going on that makes the script take a while (~4 seconds). I don't mind the processing time, but IE prompts with a warning since there are so many executions.
我已经尝试优化我的代码,但我只是可以' t减少足以绕过IE警告的执行次数。因此,我认为我必须使用setTimeout函数来重置IE中的计数器。
I've tried optimizing my code, but I simply can't cut down the number of executions enough to bypass the IE warning. Therefore, I figure that I must use the setTimeout function to reset the counter in IE.
代码很长,我只是无法弄清楚如何正确在IE中实现setTimeout。我试过模仿找到的代码,但由于某种原因,它会在第100次迭代后崩溃。
The code is quite long, and I just can't figure out how to properly implement setTimeout in IE. I've tried mimicking the code found here, but for some reason it ends up crashing after the 100th iteration.
I我不知道这是否很常见,但是如果我发送给他们,有人会介意看看代码吗?我不想在这里发帖,因为它很长。
I don't know if this is common at all, but would anyone mind taking a look at the code if I sent it to them? I just wouldn't want to post it on here because it's quite lengthy.
谢谢!
编辑:我已将我的代码放在JSfiddle上,正如一些人所建议的那样。你可以在找到它。感谢您的建议并告诉我是否有任何问题!
I've placed my code on JSfiddle as some people have suggested. You can find it here. Thanks for the suggestion and let me know if there are any questions!
推荐答案
我使用的基本方法是将工作细分为批次。每批都在一个纪元中完成,在批处理完成时,它调用setTimeout()来启动下一个纪元。
The basic approach I use is to segment the work into batches. Each batch is done in one "epoch" and at the completion of the batch, it calls setTimeout() to kick off the next epoch.
假设您有1000次迭代运行;你可以把它分成100个批次。
Suppose you have 1000 iterations to run; you can segment it into batches of 100.
function doTheWork(operation, cycles, callback) {
var self = this, // in case you need it
cyclesComplete = 0,
batchSize = 100;
var doOneBatch = function() {
var c = 0;
while(cyclesComplete < cycles) {
operation();
c++;
if(c >= batchSize) {
// may need to store interim results here
break;
}
cyclesComplete++;
}
if (cyclesComplete < cycles) {
setTimeout(doOneBatch, 1);
}
else {
callback(); // maybe pass results here
}
};
// kickoff
doOneBatch();
return null;
};
这篇关于使用setTimeout绕过IE的长时间运行脚本警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!