0

I try that my aframe-sky-component changes his image every 3sec but it´s not working. Here what i coded so far:

 <script type = "text/javascript">
   function startTimer(){
  setInterval(function(){ nextimage(); }, 3000);

   function nextimage() {
     var zahl = 0;

     if (zahl == 0) {
       $("#skyid").attr("src","#sky_2");
       zahl ++;
     }
     if (zahl == 1) {
       $("#skyid").attr("src","#sky_3");  
       zahl ++;
     }
     if (zahl == 2) {
       $("#skyid").attr("src","#sky_4");  
       zahl ++;
     }
     if (zahl == 3) {
       $("#skyid").attr("src","#sky_1"); 
       zahl ++;
     }
     if (zahl == 4) {
       zahl == 0;
     }
     }
   }
  </script>   

I guess i have some logic mistakes thx for helping :D

Delidragon
  • 165
  • 4
  • 17

1 Answers1

2

Each time you call nextImage the zahl is set to 0.

You can just move it to the outer scope:

function startTimer(){
  setInterval(function(){ nextimage(); }, 3000);
  var zahl = 0;
  function nextimage() {
  ....

like I did here. Now its not zeroed by calling nextImage() so it acts like a counter.


Also i think a bit more elegant solution is having a color array:

var colors = ["blue", "red", "green", "yellow"]
function nextimage() {
  $("#skyid").attr("color", colors[zahl])
  zahl = (zahl < colors.length - 1) ? ++zahl : 0 
  //zahl is incremented until its reached the end of the array
}
Piotr Adam Milewski
  • 14,150
  • 3
  • 21
  • 42
  • 1
    P.S. for learning purposes i'd recommend checking out [closures](https://www.w3schools.com/js/js_function_closures.asp) – Piotr Adam Milewski Jun 26 '18 at 22:48
  • thx works fine. Could you tell me how i can make that this loop forever :) – Delidragon Jun 27 '18 at 08:08
  • P.s you are right i should learn more the basics of javascript, but i learn so much (before a year i had no idea from computer) someone who gives me something which work increases my motivation soo thx a lot jesus of aframe – Delidragon Jun 27 '18 at 08:10
  • @Delidragon hey, i've made an update, there was a typo (`zahl == 0` instead of `zahl = 0`), it should be looped now. – Piotr Adam Milewski Jun 27 '18 at 08:20