Question

I have a timeout interval and want to change the color of hop1 und hop2 each interval. The color change at 1000ms, 900ms, 800ms and so on. Why does my code doesn't work?

                var interval = 1000;
                var change   = 1;

                function callback() {

                   interval -= 100; 

                              if (change = 1)
                   {
                     mainContent1 = document.getElementById("hop1");
                     mainContent1.style.backgroundColor = "#FFFF99";
                     mainContent2 = document.getElementById("hop2");
                     mainContent2.style.backgroundColor = "#FFFFFF";
                     change += 1;
                   }

                   else if (change = 2)
                   {
                     mainContent2 = document.getElementById("hop2");
                     mainContent2.style.backgroundColor = "#FFFF99";
                     mainContent1 = document.getElementById("hop1");
                     mainContent1.style.backgroundColor = "#FFFFFF";
                     change = 1;

                   }
                    setTimeout( callback, interval, change);
                 }

            setTimeout( callback, interval, change);
Était-ce utile?

La solution

change your code to this and make sure you stop calling the setTimeout after you get to the intended interval:

            var interval = 1000;
            var change   = 1;

            function callback() {

               interval -= 100; 

                          if (change == 1)
               {
                 mainContent1 = document.getElementById("hop1");
                 mainContent1.style.backgroundColor = "#FFFF99";
                 mainContent2 = document.getElementById("hop2");
                 mainContent2.style.backgroundColor = "#FFFFFF";
                 change += 1;
               }

               else if (change == 2)
               {
                 mainContent2 = document.getElementById("hop2");
                 mainContent2.style.backgroundColor = "#FFFF99";
                 mainContent1 = document.getElementById("hop1");
                 mainContent1.style.backgroundColor = "#FFFFFF";
                 change = 1;

               }
                setTimeout( callback, interval);
             }

        setTimeout( callback, interval);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top