Bypassing IE's long-running script warning using setTimeout
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.
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.
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 end开发者_如何学Gos up crashing after the 100th iteration.
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.
Thanks!
EDIT: 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!
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.
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;
};
精彩评论