I have a data set, over which I iterate and run a fairly heavy operation on each element. To prevent the browser from freezing, I've set a timeout of 0ms. While the browser doesn't freeze, the calculation can take a good few seconds depending on user input. Here's the code:
function calculation(){
$.each(data,function(key,value){
setTimeout(function(){
doTheHeavyLifting(value);
},0);
});
}
Now, the problem is, that I want to stop the previous calculation if the user requests to run the calculation again with new values.
I tried defining a continueCalculating boolean outside the function, and setting that to false in runCalculation() before calling calculation(), and inside calculation() resetting it back to true. Here's the modified code:
var continueCalculating=false;
function runCalculator(){
continueCalculating=false;
calculation();
}
function calculation(){
continueCalculating=true;
$.each(data,function(key,value){
setTimeout(function(){
if(continueCalculating){
doTheHeavyLifting(value);
}else{
console.log("Abort the mission!");
return false;
}
},0);
});
}
Well, that didn't do the trick, and in retrospect was a pretty silly idea anyway. So, next I tried also clearing all the timeouts. Here's the modified code:
var continueCalculating=false;
var operationQueue=[];
function runCalculator(){
continueCalculating=false;
$.each(operationQueue, function(k,v){
clearTimeout(v);
});
calculation();
}
function calculation(){
continueCalculating=true;
$.each(data,function(key,value){
operationQueue.push(setTimeout(function(){
if(continueCalculating){
doTheHeavyLifting(value);
}else{
console.log("Abort the mission!");
return false;
}
},0));
});
}
Well, that didn't yield any results either.
I know $.each is slower than for, but there are only about a couple dozen items to iterate over, so it certainly isn't the bottle neck here. I'm not looking for ways to optimize this code, I just need to stop an on-going calculation. Is this possible?
Aucun commentaire:
Enregistrer un commentaire