countermb countermb - 3 days ago 5
Javascript Question

Changing a heading every few seconds, with an array and a loop

I'm trying to create a html heading that changes itself every 5 seconds, through an array of multiple items and a loop. I can get everything to work, except the text changing after every fifth second. Right now, it immediately goes from the first item in the array, to the last. I've tried using setTimeOut and setInterval, but no luck so far. I've also searched everywhere online.

Here's what i have so far, without the setTimeOut/setInterval part, because it didn't work:

var headingChange = {

heading: function() {
var headings = ['Hello', 'Hi', 'Ye'];
for (var i = 0; i < headings.length; i++) {
document.getElementById('heading').innerHTML = headings[i];
}
}
};


Here's a jsfiddle to make it easier (+ html).

https://jsfiddle.net/countermb/w9qwk6ch/

Hope someone can help me (am new to Javascript). Thanks in advance.

A.J A.J
Answer

This Snippet might help you.

You may need to use setInterval to change the heading.

var headings = ['Hello', 'Hi', 'Ye'];
var i = 0;
var intervalId = setInterval(function() {
  document.getElementById('heading').innerHTML = headings[i];
  if (i == (headings.length - 1)) {
    i = 0;
    //you can even clear interval here to make heading stay as last one in array
    //cleanInterval(intervalId);

  } else {
    i++;
  }
}, 4000)
<h1 id="heading">Change this!</h1>

Comments