1

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.

Rubioli
  • 685
  • 6
  • 34
  • 1
    Possible duplicate of [Generating random whole numbers in JavaScript in a specific range?](http://stackoverflow.com/questions/1527803/generating-random-whole-numbers-in-javascript-in-a-specific-range) – Liam Mar 09 '17 at 11:50
  • @Liam Its not a duplicate topic. In that topic, you are generating a random number only. What I looking for is to update `setInterval` `delay` value by having `Interval` for itself as well in `jQuery`. – Rubioli Mar 09 '17 at 11:55

1 Answers1

2

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());
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Thanks @Rory. Works great :) . I have only one question. I only want to run the loop once and I managed to do this by doing `iframe.attr("src", locations[++i])` in my `setSrc()` function. Is it correct? and I see that after I have done the loop once, `getDelay()` function still runs. How can I make it so when loop is done, it does stop. Thanks – Rubioli Mar 09 '17 at 13:03
  • Thanks a bunch :) – Rubioli Mar 09 '17 at 13:34