Question

I am using following code to delay a loop, It is working perfectly, but I want to delay only specific iterations. I want to delay when j is 3 or 8. what should I do?

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

Solution

Something like this? It uses setTimeout rather than 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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top