Search code examples
jquerydelaysetintervalupdating

Update setInterval value, with interval for itself (Not generating a random number)


With jQuery I am changing iframe src, every 60 sec (This works fine).

My jQuery:

$(document).ready(function(){
  var array = ['http://link1.com', 'http://link2.com', 'http://link3.com'];
  var locations = array;
  var len = locations.length;
  var iframe = $('#frame');
  var i = 0;
  setInterval(function () {
        iframe.attr('src', locations[++i]);
  }, 60000);

});

My iframe:

<iframe id="frame" src="http://link.com"></iframe>

My iframe src function works fine and what I would like to achieve is, instead of having a fixed delay number (now 60 sec), I would like to change the delay value as well, each time iframe src has been updated.

The new delay number will be a random number between 15 & 30 secs.


Solution

  • You cannot change an interval once it's been defined. A workaround for this would be to chain setTimeout() calls, generating a random delay between each call something like this:

    var locations = ['http://link1.com', 'http://link2.com', 'http://link3.com'];
    var i = 0;
    
    setTimeout(setSrc, getDelay());
    
    function setSrc() {
      console.log(locations[++i % locations.length]);
      setTimeout(setSrc, getDelay());
    }
    
    function getDelay() {
      var delay = (Math.floor(Math.random() * 30) + 15) * 1000;
      console.log('waiting: ' + delay);
      return delay;
    }

    How can I make it so when loop is done, it stops?

    In this case you can check if i > locations.length and then not call the function again:

    function setSrc() {
      console.log(locations[++i]);
      if (i < locations.length)
        setTimeout(setSrc, getDelay());
    }