javascript - Mootools 每 5 秒暂停一个 Array.each 循环

标签 javascript arrays mootools

我有一个 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/

相关文章:

Javascript Unicode 转义反斜杠

javascript - 如何使用文本文件中的 d3.js 绘制直方图,而不是使用 map 随机生成

javascript - 如何打开/关闭 $(document).click() 事件或其他解决方案

arrays - 对包含另一个可选项的可选项数组进行排序

javascript - 使用嵌套函数查找第二大数字。查找最大数的函数会覆盖原始数组

javascript - 如何在mootools中同时执行多个动画?

javascript - 如何通过 API 创建工作表后获取 Google Sheet Id?

内部函数可以使用父函数中定义的变量吗?

javascript - Google maps infoWindow - 关闭时会破坏内容吗?

css - IE7 ul显示:none/block problem