我有一个 Array.each 函数,每次循环运行 25 次时我都需要暂停 5 秒。
Array.each(response.data, function(thing, index){
sendEmail(thing.id,sku,thing.email);
});
我尝试了各种方法,但它总是毫不延迟地调用 sendEMail 函数。有谁知道如何做到这一点?
循环可能会运行 15 到 500 次,具体取决于发送给它的数据。
谢谢。
Mootools 1.4.5
最佳答案
除非 Array.each
允许您从传入的回调中提前退出并允许您从任意索引。然后您仍然需要围绕它进行逻辑处理来处理暂停。
另一种方法是自己动手。
var eachWithPause = function( iterable, iterations, timeout, fn, ctx ) {
// Sets up a callback to be passed back to the caller, allowing them
// to cancel the `setTimeout` call created within `loop`.
var timeoutID = 0;
var cancel = function() {
clearTimeout( timeoutID );
};
// `loop` will run the desired number of iterations, or iterate through
// the remainder of the `iterable`, whichever comes first. If there are
// still elements left after it is done, it will `setTimeout` for the
// desired amount of time.
var index = 0, l = iterable.length;
var loop = function() {
for ( var i = 0; i < iterations && index < l; ++i, ++index ) {
fn.call( ctx, iterable[ index ], index, iterable );
}
if ( index < l ) {
timeoutID = setTimeout( loop, timeout );
} else {
timeoutID = 0;
}
};
loop();
return cancel;
};
我在这里做的唯一有趣的事情是返回一个 cancel
函数,它将为调用者提供一种在不断变化的 上调用
。clearTimeout
的方法它无权访问的 setTimeout
然后你会得到类似的东西
var cancel = eachWithPause(response.data, 5, 5000, function(thing, index) {
sendEmail(thing.id, sku, thing.email);
});
如果你需要取消这个操作,你可以简单地cancel()
它。
关于javascript - Mootools 每 5 秒暂停一个 Array.each 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14888196/