如何在每个循环的JQuery中进行可变延迟/休眠

时间:2018-05-29 14:40:53

标签: javascript jquery foreach settimeout

我已经看到很多其他人提出了与此有关的问题,但没有一个答案确实有效并且不适用于我的情况。

我只是想在我的每个可变时间长度循环中实现延迟。这些可变时间长度来自我在读取json文件时循环的数组。为了给出进一步的上下文,目的是突出一个句子中的每个单词一段可变的时间 - 每个单词都有一个与json文件相关的时间(以毫秒为单位)。

我的假设是解决方案与setTimeout有关,但每次我尝试它最初都会等待,但然后跳过所有其余的。

我的代码现在:

  $("[id^='timing_check']").click(function() {
    sn = $(this).attr('name');
    ayahnum = $(this).attr('data-id');

    $.getJSON("/static/json/mishary.json", function(result) {
      $.each(result, function(i, v) {
        if (v.ayah == ayahnum && v.surah == sn) {
          var x = v.segments;
          var i = 1;

          x.forEach(function(item) {
            time_sleep = item[3];
            wordref = sn + ':' + ayahnum + ':' + i;
            i++;

            setTimeout(function() {
              $("[name='" + wordref + "']").css('color', 'red');
            }, time_sleep);
          });
        }
      });
    });
  });
});             

这根本不起作用。差远了。请提供一些指导

1 个答案:

答案 0 :(得分:1)

我认为问题如下,让我们假设这段代码:

array1 = [1000, 2000, 1000, 4000, 10000];
array1.forEach(function(item) { //all actions start at 0

        setTimeout(function() {
            console.log("some action of item "+item);
        }, item);

    }

);

所有setTimeout函数都是从 0 + item 时间计算出来的,因此1000和1000的时间将同时执行。也许你想像 item [i1] + item [i2] 那样考虑时间,那么你必须总结每次迭代所花费的所有时间。这种方式的代码就像:

array1 = [1000, 2000, 1000, 4000, 10000];

var abs = 0;//beginning 

array1.forEach(function(item) {

        if(!abs){
            abs = item;
        }else{
            abs += item;//sum time spent
        }
        console.log("set "+abs+" to setTimeout");

        setTimeout(function() {
            console.log("some action of item "+item);
        }, +abs);

    }

);

在这个例子中,第2个1000将在1000和2000之后计算,即在激活循环后的4000毫秒。