如何更改代码以同时启动SetTimeout?

时间:2019-01-17 20:51:28

标签: javascript settimeout

如何更改我的代码以同时开始闪烁并且仍然无限闪烁?

function blink(){     如果(!toggleSwitch){

    for (let i = 0; i < elements.length; i++) {
        shapes.push(elements[i].className);

    }
    // Start off at the first element.
    let i = 0;
    let len = shapes.length;

    // Do the next link
    function doNext() {

        let element = shapes[i];
        i++;

        eval(element).fillColor = eval(element).setColor;
        document.getElementById(element).style.backgroundColor = (eval(element).fillColor===document.getElementById(element).style.backgroundColor) ? 'white' : eval(element).setColor ;

        if (i < len) {
            // Don't do anything special
        }  else {
            // Reset the counter
            i = 0;
        }
        myVar = setTimeout(doNext, 1000);      }

    // And the code needs kicked off somewhere
    doNext();
}

} 同样,我也无法切换类,因为通过拖放操作,我可以在运行时随时更改背景颜色,因此每个形状都有一个对象,其中背景是什么颜色。 –

1 个答案:

答案 0 :(得分:0)

我认为您正在寻找的是setInterval。有关基本的功能闪烁示例,请参见下文。

let red = true;
let squares = document.querySelectorAll('.square');
  
setInterval(() => {
  red = !red;
  for (let i = 0; i < squares.length; i++) {
    if (red) squares[i].className = 'square red';
      else squares[i].className = 'square';
  }
}, 2000);
.square {
  height: 50px;
  width:50px;
  margin:10px;
  background-color: #FFF;
}

.red {
  background-color: #F00;
}
<div class="square red"></div>
<div class="square red"></div>
<div class="square red"></div>
<div class="square red"></div>