Debajeet Choudhury
Debajeet Choudhury

Reputation: 389

setInterval time not getting correct value

I have two arrays. One of files and another for time I want to display them in an iframe. I loop through them the files appear correctly but the time is always set to the first element.

The iframe always loads for 10000 ms.

$(function() {
  var urls = ['/uploads/presentations/1560837902.pdf', '/uploads/presentations/1560837925.mp4', '/uploads/presentations/1560837959.jpg', '/uploads/presentations/1560838138.docx', '/uploads/presentations/1560838215.ppt'];
  var time = [10000, 40000, 10000, 20000, 10000];
  var i = 0;

  function loadIframe(url) {
    $('#iframe').attr('src', url);
  }

  setInterval(function() {
    // update the index
    i = (i + 1) % urls.length;
    loadIframe(urls[i]);
  }, time[i]);

  loadIframe(urls[i]);
});

Upvotes: 1

Views: 127

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is because you only define a single interval, hence the delay is always the same.

To fix this you could use a recursive timeout instead, defining the next when the previous fires. Try this:

$(function() {
  var urls = ['/uploads/presentations/1560837902.pdf', '/uploads/presentations/1560837925.mp4', '/uploads/presentations/1560837959.jpg', '/uploads/presentations/1560838138.docx', '/uploads/presentations/1560838215.ppt'];
  var time = [10000, 40000, 10000, 20000, 10000];

  function loadIframe(i = 0) {
    $('#iframe').attr('src', urls[i % urls.length]);
    console.log(`Changing src to ${urls[i % urls.length]}`);
    
    setTimeout(function() {
      loadIframe(++i);
    }, time[i % time.length]);
  }

  loadIframe();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 4

Related Questions