Вопрос

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);
Это было полезно?

Решение

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);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top