Pure Javascript - setInterval (1s), setAttribute

▼魔方 西西 提交于 2019-12-02 06:38:26

It is not an attribute you want to set but a style:

thesquare.style.backgroundColor = 'red';

Your function does work but the attribute background-color does not do anything.

Also, setInterval("changecolor()",1000); should be setInterval(changecolor,1000);

Fiddle

Next thing, every second document.getElementById('myID') is written to a new formed variable thesquare. How to make the variable global, outside the function?

You don't need to use a global, you can keep it in an outer scope using a closure and an immediately invoked function expression (IIFE):

(function() {
  var thesquare = document.getElementById('myID');
  var i = 0;

  function changecolor() {
    switch (i) {
        case 0 :
          thesquare.style.backgroundColor = "red";
          ++i;
          break;

        case 1 :
          thesquare.style.backgrounColor = "green";
          ++i;
          break;

        default :
          thesquare.style.backgroundColor = "blue";
          i=0;
          break;
    }
  }
  setInterval(changecolor, 1000);
}());

Note that setInterval will run at about, not exactly, the specified interval. It will slowly lose time.

You can shorten the code by replacing the entire switch block with something like:

   var colours = ['red','green','blue']
   thesquare.style.backgroundColor = colours[i++ % colours.length];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!