我在同一条船上。我有点喜欢Node的异步函数,所以我写了这个异步For和ForEach函数。它使用“setTimeout(Func,0);”技巧。
这里是图书馆:
var WilkesAsyncBurn = function()
{
var Now = function() {return (new Date());};
var CreateFutureDate = function(milliseconds)
{
var t = Now();
t.setTime(t.getTime() + milliseconds);
return t;
};
var For = function(start, end, eachCallback, finalCallback, msBurnTime)
{
var i = start;
var Each = function()
{
if(i==-1) {return;} //always does one last each with nothing to do
setTimeout(Each,0);
var burnTimeout = CreateFutureDate(msBurnTime);
while(Now() < burnTimeout)
{
if(i>=end) {i=-1; finalCallback(); return;}
eachCallback(i);
i++;
}
};
Each();
};
var ForEach = function(array, eachCallback, finalCallback, msBurnTime)
{
var i = 0;
var len = array.length;
var Each = function()
{
if(i==-1) {return;}
setTimeout(Each,0);
var burnTimeout = CreateFutureDate(msBurnTime);
while(Now() < burnTimeout)
{
if(i>=len) {i=-1; finalCallback(array); return;}
eachCallback(i, array[i]);
i++;
}
};
Each();
};
var pub = {};
pub.For = For; //eachCallback(index); finalCallback();
pub.ForEach = ForEach; //eachCallback(index,value); finalCallback(array);
WilkesAsyncBurn = pub;
};
示例用法:
WilkesAsyncBurn(); // Init the library
console.log("start");
var FuncEach = function(index)
{
if(index%10000==0)
{
console.log("index=" + index);
}
};
var FuncFinal = function()
{
console.log("done");
};
WilkesAsyncBurn.For(0,2000000,FuncEach,FuncFinal,50);
prints:
index=10000
index=20000
index=30000
etc
"done"
如有兴趣,请进行更多研究:
setTimeout和setInterval的最小开销时间约为2到10毫秒,因此,无缘无故地启动数千或数百万个计时器会很慢。所以基本上,如果你需要在不锁定浏览器的情况下执行数千个或更多的循环,你需要更像一个线程(喘息),并在设定的时间内“燃烧”一些代码,而不是设定迭代次数。