在setInterval()中暂停或延迟数组上的循环

时间:2015-07-05 10:44:49

标签: javascript setinterval

我希望我创建的框的颜色每0.5秒更改一次,我已将颜色存储在数组中,我希望颜色每隔0.5秒更改一次,但它会一次全部更改。

<style type="text/css">
    #box{
        width: 100px;
        height: 100px;
        background: green;
    }
</style>

</head>

<body>  
    <div id="box"></div>

    <script type="text/javascript">
        var colors = ['red','blue','green','violet','purple'];
        var box = document.getElementById('box');

        setInterval(function(){
            for(var i=0; i < colors.length; i++){
                box.style.backgroundColor=colors[i];
            }   
        }, 300);
    </script>

4 个答案:

答案 0 :(得分:2)

您正在间隔回调中循环,这意味着它将遍历每个间隔的所有颜色。

使间隔成为循环,即每个间隔更进一步。例如:

var index = 0;

setInterval(function(){
  box.style.backgroundColor = colors[index];
  index = (index + 1) % colors.length;
},300);

演示:

var colors = ['red','blue','green','violet','purple'];
var box = document.getElementById('box');

var index = 0;

setInterval(function(){
  box.style.backgroundColor = colors[index];
  index = (index + 1) % colors.length;
},300);
#box{
            width: 100px;
            height: 100px;
            background: green;
        }
<div id="box"></div>

注意:要实际获得每0.5秒运行一次的间隔,您应在setInterval调用中使用500而不是300。

答案 1 :(得分:2)

根据您是否希望盒子在通过所有颜色后继续更改,有多种方法可以解决此问题:

/*
 Keeps running
*/
var colors = ['red','blue','green','violet','purple'],
    i = 0;

setInterval(function () {
   
  box.style.backgroundColor = colors[i++ % colors.length];
  
}, 500);


/*
 Runs once only
*/
var colorsOnce = colors.slice(),
interval = setInterval(function () {
   
  once.style.backgroundColor = colorsOnce.shift();
  if(!colorsOnce.length) clearInterval(interval);
  
}, 500);
.box{
  width: 100px;
  height: 100px;
  background: green;
}
<div id="box" class="box"></div>
<div id="once" class="box"></div>

注意:尽管有这些示例,但涉及计时功能的最佳做法通常是使用上述@AmmarCSE所描述的超时。

答案 2 :(得分:1)

使用setTimeout()

&#13;
&#13;
var colors = ['red', 'blue', 'green', 'violet', 'purple'];
var box = document.getElementById('box');

for (var i = 0; i < colors.length; i++) {
  (function(index) {
    setTimeout(function() {
      console.log(index);
      box.style.backgroundColor = colors[index];
    }, 300 * i);
  })(i)
}
&#13;
#box {
  width: 100px;
  height: 100px;
  background: green;
}
&#13;
<div id="box"></div>
&#13;
&#13;
&#13;

答案 3 :(得分:1)

您在代码中遗漏的两个要点

  1. 半秒是“500毫秒”。因此,您需要在setInteval中将300毫秒更改为500毫秒。
  2. 当计时器启动时,您需要使用“阵列中的下一个颜色”更新背景颜色。
  3. 所以你可以试试像:

    var color = 0;
    var colors = ['red','blue','green','violet','purple'];
    function nextColor(){
        color ++;
        if (color>=colors.length)
            color = 0;
        return colors[color];
    }
    
    setInterval(function(){
        box.style.backgroundColor = nextColor();   
    },500);
    

    这将使盒子每隔半秒改变颜色,并无休止地循环通过颜色阵列。

相关问题