title: How To Automatically Change An HTML Image Using JavaScript
body: <p>NB: <strong><em>I've had a look <a href="https://stackoverflow.com/questions/13975891/change-image-in-html-page-every-few-seconds">here</a> for how to change the images on a timer, as oppose to using buttons, but it didn't cater to my code style.</em></strong></p>
  
  <p>As I'm new to HTML and JS I still don't understand all the aspects and got a little confused on which part they were referring to in translation to how I wrote my code.</p>
  
  <p>CODE:</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
    &lt;body&gt;
      &lt;img id="image" src="blank_light.jpg" style="width:100px"&gt;
      &lt;p&gt;&lt;/p&gt;
      &lt;button class="change-image"&gt;Change Lights&lt;/button&gt;
      &lt;script&gt;
        var imageSources = ["red_light.jpg", "red_and_yellow_light.jpg", "yellow_light.jpg", "green_light.jpg"]
        var buttons = document.getElementsByClassName("change-image")[0];
        var index = 0;
  
        buttons.addEventListener('click', function() {
          if (index === imageSources.length) {
            index = 0;
          }
          document.getElementById("image").src = imageSources[index];
          index++;
        });
  
      &lt;/script&gt;
    &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>I need to remove the buttons and have the images change on a <em>timed</em> basis instead. Ideally every 2 seconds.</p>
  
  <p>Thanks in advance.</p>