2

This script changes DIV text every 5 seconds, but, It starts after 5 seconds, how do i make a first text change once page loads and then every 5 secs ?

var text = ["1", "2", "3", "4", "5"];
var counter = 0;
var elem = document.getElementById("textas");
var inst = setInterval(change, 5000);

function change() {
  elem.innerHTML = text[counter];
  counter++;
  if (counter >= text.length) {
    counter = 0;
    // clearInterval(inst); // uncomment this if you want to stop refreshing after one cycle
  }
}
chazsolo
  • 7,873
  • 1
  • 20
  • 44
bocanaco
  • 21
  • 1
  • 5
    call change() and then immediately set the interval? – Steve0 Oct 18 '18 at 20:09
  • 2
    Why not just fire `change()` on page load? Then the setInterval will do it's thing. http://jsfiddle.net/nvu90cy2/1/ – justDan Oct 18 '18 at 20:09
  • 4
    Possible duplicate of [Execute the setInterval function without delay the first time](https://stackoverflow.com/questions/6685396/execute-the-setinterval-function-without-delay-the-first-time) – André DS Oct 18 '18 at 20:27

1 Answers1

1

Call the change function once, indirectly from the setInterval method.
Furthermore, you could set a maximum number, instead of using an array which contains all of your iterations.

var counter = 0,
    maxNumber = 5,
    elem = document.getElementById('textas'),
    inst = setInterval(change, 5000);

function change() {
  counter++;
  elem.innerHTML = counter;
  if (counter >= maxNumber) {
    counter = 0;
  }
}

change();
<h1 id="textas"></h1>
Quentin Veron
  • 3,079
  • 1
  • 14
  • 32
  • You could reduce this a little by using the modulus operation for `counter = ++counter % maxNumber;` – Taplar Oct 18 '18 at 22:14
  • It's no doubt shorter, but I would have to set `maxNumber` to **6** to be able to reach the number **5**, which might be a little confusing. – Quentin Veron Oct 18 '18 at 22:23
  • 1
    Your number would never be five anyway. 4 becomes 5, then 5 == 5, so it becomes zero. same thing with 4 becoming 5, 5 % 5 becomes zero – Taplar Oct 18 '18 at 22:27
  • Indeed. I made a little error. I should have use **innerHTML** before to clear **count**. I edit my answer. – Quentin Veron Oct 18 '18 at 22:30
  • Actually this answer deviates from the OP as it is now. It's not using the array they are trying to use. – Taplar Oct 18 '18 at 22:30
  • As he is using this array and with that little information provided, I thought it was better not to use the array. Looks more like he didn't know he doesn't have to store each iteration. – Quentin Veron Oct 18 '18 at 22:35