countermb countermb - 2 months ago 15
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).

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


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

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