Altin I. Sylejmani
Altin I. Sylejmani

Reputation: 65

How to change an image every 5 seconds for example?

I have three images in my HTML code, and I want them to change every five seconds. Why does my code not work?

var images = [];

images[0] = ['photoFromInternet'];
images[1] = ['photoFromInternet2'];
images[2] = ['photoFromInternet3'];
var index = 0;

function change() {
  document.mainPhoto.src = images[index];
  if (index == 2) {
    index = 0;
  } else {
    index++;
  }

  setInterval(change(), 1000);
}

window.onload = change();
<div class="lastMain">
  <a href="www.comingsoon.com" id="slider">
    <img id="mainPhoto">
    <div class="mainSlider">
      <img src="photoFromInternet1" style="display: none">
      <img src="photoFromInternet2*" style="display: none">
      <img src="photoFromInternet3" style="display: none">
    </div>
  </a>
</div>

P.S. If you can help please don't use jquery because I haven't learned that yet.

Upvotes: 2

Views: 22650

Answers (2)

mars328
mars328

Reputation: 573

you should run 'change' function outside of the func and pass the function name to the setInterval func as below

let images = ['photoFromInternet', 'photoFromInternet2', 'photoFromInternet3'];

let index = 0;
const imgElement = document.querySelector('#mainPhoto');

function change() {
   imgElement.src = images[index];
   index > 1 ? index = 0 : index++;
}

window.onload = function () {
    setInterval(change, 5000);
};

Upvotes: 8

Jeremy Thille
Jeremy Thille

Reputation: 26360

Look at your console, it's telling you why. Uncaught TypeError: Cannot set property 'src' of undefined, meaning document.mainPhoto is undefined. That's not how you select an element in JS (document.getElementById("mainPhoto") works better :)

Also, you should pass a function to setInterval, not call the function directly inside of it, otherwise you are infinitely calling change() which leads to an infinite call stack error.

Also, if you want 5 seconds, you want to pass 5000, not 1000 (milliseconds).

Finally, you want to set a timeout, not an interval, every time you call the function. Timeouts are executed once. If you set a new interval every time, you'll be piling up function calls exponentially, quickly making your page unresponsive by overwhelming the CPU.

var images = [];

images[0] = ['photoFromInternet'];
images[1] = ['photoFromInternet2'];
images[2] = ['photoFromInternet3'];
var index = 0;

function change() {
  document.getElementById("mainPhoto").src = images[index];
  if (index == 2) {
    index = 0;
  } else {
    index++;
  }

  setTimeout(change, 5000);
}

window.onload = change();
<div class="lastMain">
  <a href="www.comingsoon.com" id="slider">
    <img id="mainPhoto">
    <div class="mainSlider">
      <img src="photoFromInternet1" style="display: none">
      <img src="photoFromInternet2*" style="display: none">
      <img src="photoFromInternet3" style="display: none">
    </div>
  </a>
</div>

Upvotes: 1

Related Questions