我想去更通用的塊組方法。
Array.implement({
chunkEach: function(offset, count, delay, fn, bind){
// get a chunk
var newOffset = offset + count,
chunk = this.slice(offset, newOffset),
ii = 0,
len = chunk.length;
if (!len)
return this;
// loop the chunk supporting natural index.
for (; ii< len; ++ii)
fn.call(bind, chunk[ii], offset + ii);
// move pointer and self call
if (newOffset < this.length)
this.chunkEach.delay(delay, this, [newOffset, count, delay, fn, bind]);
// pointless chaining return as its async.
return this;
}
});
使用,在以2秒鐘的暫停的15塊的電子郵件地址的例如環陣列,保持的功能範圍的假想物體與選項屬性:
list.chunkEach(0, 15, 2000, function(el, index){
console.log(this.options);
new Element('div[html='+index + '. ' + el +']').inject(o);
}, this);
看到http://jsfiddle.net/dimitar/aYwab/
其粗糙 - 缺乏對參數和東西的檢查,但它會做你想做的。
可能存在關於在此解決延遲的責任的問題。你正在發送電子郵件,大概是通過Ajax。不明確的延遲是不可縮放的。
你應該看看使得sendEmail
功能可鏈接 - 簡單數組和索引傳遞到它,如果指數小於數組長度 - 1,再次從onSuccess
下一個指數叫sendEmail
。這還允許您在上次發送失敗時中斷或重試。
另外,你可以使用Promise。
不要嘗試暫停循環。相反,使用計時器並從其回調中循環塊數據。 – bfavaretto 2013-02-15 04:37:07