更改颜色与超时结合

时间:2014-03-15 18:17:11

标签: colors timeout intervals

我有一个超时间隔,想要改变每个间隔的hop1和hop2的颜色。颜色在1000ms,900ms,800ms等变化。为什么我的代码不起作用?

                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);

1 个答案:

答案 0 :(得分:1)

将代码更改为此代码,并确保在达到预期的时间间隔后停止调用setTimeout:

            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);