特定迭代的循环延迟

时间:2014-05-09 09:44:20

标签: javascript loops timer

我正在使用以下代码来延迟循环,它工作正常,但我想只延迟特定的迭代。当j为3或8时我想延迟。我该怎么办?

        var j=0;
        var timer = setInterval(function () {
            $("#followcounter").text(j);
             j++;
            if (j > 10) {
                $("#followcounter").text("End all ");
                clearTimeout(timer);
            }
        }, 5000);

1 个答案:

答案 0 :(得分:1)

这样的东西?它使用setTimeout而不是setInterval

var write = function (count) {
  $('#followcounter').text(count);
};

var count = 0;

function looper() {
  count++;
  var delay = (count === 3 || count === 8) ? 5000 : 1
  var timer = setTimeout(function () {
    if (count > 10) {
      $('#followcounter').text('End all');
      clearTimeout(timer);
    } else {
      write(count);
      looper();
    }
  }, delay);
};

looper();

Demo