-1

I have no clue why. I have checkt everything but it should work. This shuld be a slidshow for a webseit

<script src="JS/javascript.js">
    "use strict";
    var image = ['"bilder/1.png"','"bilder/2.png"'];
    var i = 0;

    aengereHintergrund();

    function aengereHintergrund() {
      document.getElementById('hintergund').style.backgroundImage = 'url('+image[i]+')';
      if(i < image.length){
      i ++

      }
      else {
        i = 0
      }
     setTimeout(aengereHintergrund(),3000);
    }
   </script>
Philipp
  • 5
  • 2

2 Answers2

0

Oh, the classic function reference vs invocation problem.

Here's what you wrote:

setTimeout(aengereHintergrund(),3000);

And here's what you should have written:

setTimeout(aengereHintergrund,3000);

In the second case, we're passing the function aengereHintergrund itself to setTimeout, which is what we want. In the first case, you're invoking aengereHintergrund, and passing its result (which is nothing, aka undefined) to setTimeout.

(Note: You should also probably use setInterval instead of setTimeout, so you don't have to invoke it again and again. Also also, instead of branching on i >= image.length you can just use i = (i + 1) % image.length).

Máté Safranka
  • 4,081
  • 1
  • 10
  • 22
0

If you write if (i < images.length) i++;, i will reach images.length. You can fix this error with i++; if (i >= images.length) i = 0;, or i = (i + 1) % images.length; :

var slides = document.getElementById("slides");
var images = ["v67W6.jpg", "USehe.jpg"];
var path = "https://i.stack.imgur.com/";
var i = 0;

nextSlide();

function nextSlide () {
  var bg = "url(" + path + images[i] + ")";
  slides.style.backgroundImage = bg;
  i = (i + 1) % images.length;
  setTimeout(nextSlide, 1000);
};
<img id="slides" width="300" height="100" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">