0

I use an endless loop of a each() with setInterval and setTimeout in this way:

var links = [];
links = ['zuinfos-1-tab', 'zuinfos-2-tab', 'zuinfos-3-tab', 'allgemein-tab'];
var init = 5000
var z = 0;
var n = new Date().getTime()

setInterval(function() {
  $(links).each(function(index, value) {
    setTimeout(function() {
      $('a#' + value).trigger('click');
      var j = new Date().getTime()
      var diff = j - n
      console.log(z + '\t' + index + '\t' + value + '\t' + diff);
    }, 5000 * index)
  });
  z++;
}, init * 4)
    
    

All is fine, but the first setInterval comes too late. I have to set it to init * 4, because there are four elements in each-loop. At the beginning it should start with init * 1.

I tried with a counter like this:

}, z==1?init:init*4 )

But this does not work.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Lissy
  • 11
  • 1
  • To debug this we really need to see a working example, so that we can see the timing in action, and also to understand exactly what this code does as I am 99% certain there's a less convoluted way of doing whatever you require. – Rory McCrossan Jul 23 '21 at 08:54
  • [Similar issue here](https://stackoverflow.com/q/68470984/2181514) - nesting multiple `setTimeout` inside a `setInterval` will cause you no end of headaches. – freedomn-m Jul 23 '21 at 09:14

1 Answers1

0

The issue with

setInterval(..., z==1?init:init*4)

is that the interval is only calculated once, not on every loop.

If you move the callback to its own function, you can call it from an initial setTimeout then from a setInterval on that first call, eg:

function autoLinkClicker()
{
    $(links).each(function(index, value) {
        setTimeout(function() { ... }, 5000 * index);
    });
}

setTimeout(function() { 
    autoLinkClicker();
    setInterval(autoLinkClicker, init*4);
}, init);
freedomn-m
  • 27,664
  • 8
  • 35
  • 57