【问题标题】:How to make an infinite loop with delay in JavaScript?如何在 JavaScript 中创建一个有延迟的无限循环?
【发布时间】:2014-10-19 14:16:19
【问题描述】:

我正在尝试制作可以改变颜色的 div。这是我的代码:

window.onload = function () {
    for (;;){
        setTimeout(function () {
            document.querySelector('style').style.backgroundColor = colors[rand(colors.length)];
        }, 2000);        
    }
}

var colors = [
    'red',
    'green',
    'blue',
    'yellow',
    'magenta',
    'pink'
];


var rand = function (max) {
    return Math.floor(Math.random() * max);
};
.style{
    background-color: pink;
    top: 50px;
    left: 50px;
    height: 50px;
    width: 50px;
}
<body>
  <div class="style"></div>
  </body>

但我不知道为什么它不起作用。
编辑:该脚本还会使浏览器崩溃

【问题讨论】:

  • 在这里也添加您的代码。有一个原因你不能在这里包含没有任何代码的 jsfiddle 链接。
  • 对于拥有超过 100 个代表的人来说,格式很糟糕......
  • 你有一个无限循环,这就是原因。 setTimeout 回调永远无法执行,因为事件循环无法继续下一个滴答声。
  • @FelixKling 实际上这不是一个无限循环,而是我会说用新的setTimeout 任务无休止地填充任务队列。浏览器崩溃的原因只是堆栈溢出。

标签: javascript


【解决方案1】:

单个元素

假设你的标记是这样的:

<body>
    <div id="my-id"></div>
</body>

要创建“颜色循环”,您必须使用setInterva() 设置一个函数,该函数将无限次执行(具有定义的时间间隔)以更改颜色。这是正确的代码:

var cur_color = -1,
    colors = [
        'red',
        'green',
        'blue',
        'yellow',
        'magenta',
        'pink'
    ];

var myInterval = setInterval(function() {
    document.getElementById('my-id').style.backgroundColor = colors[(++cur_color) % colors.length];
}, 2000);

这将每 2 秒更改一次颜色。如果你想阻止它,你可以使用clearInterval()函数:

clearInterval(myInterval);

多个元素

假设您的标记是:

<body>
    <div class="my-class"></div>
    <div class="my-class"></div>
    <div class="my-class"></div>
</body>

您可以改用getElementsByClassName() 方法:

var myInterval = setInterval(function() {
    var elements = document.getElementsByClassName('my-class');
    ++cur_color;
    for (var i=0; i<elements.length; i++) elements[i].style.backgroundColor = colors[cur_color % colors.length];
}, 2000);

工作示例

这是一个包含多个元素的工作示例:

var cur_color = -1,
    colors = [
        'red',
        'green',
        'blue',
        'yellow',
        'magenta',
        'pink'
    ];

var myInterval = setInterval(function () {
    var elements = document.getElementsByClassName('my-class');
    ++cur_color;
    for (var i = 0; i < elements.length; i++) elements[i].style.backgroundColor = colors[cur_color % colors.length];
}, 2000);
.my-class {
    background-color: pink;
    top: 50px;
    left: 50px;
    height: 50px;
    width: 50px;
    margin: 10px;
}
<body>
    <div class="my-class"></div>
    <div class="my-class"></div>
    <div class="my-class"></div>
<body>

【讨论】:

    【解决方案2】:

    您需要setInterval 函数。

    另外,您需要.style 选择器(类选择器)而不是style。如果你使用,你可以使用$(".style")而不是document.querySelector(...)

    window.onload = function() {
      setInterval(function() {
        document.querySelector('.style').style.backgroundColor = colors[rand(colors.length)];
        //$('.style').css("backgroundColor", colors[rand(colors.length)]);
      }, 2000);
    }
    
    var colors = [
      'red',
      'green',
      'blue',
      'yellow',
      'magenta',
      'pink'
    ];
    
    
    var rand = function(max) {
      return Math.floor(Math.random() * max);
    };
    .style {
      background-color: pink;
      top: 50px;
      left: 50px;
      height: 50px;
      width: 50px;
    }
    <body>
      <div class="style"></div>
    </body>

    【讨论】:

    • 根本不需要jQuery。
    • @MarcoBonelli 真的,问题不是用 jQuery 标记的吗?
    • @MarcoBonelli 我明白了,但我正在检查 jQuery 问题......也许我是从最新的问题来到这里的?大概……
    【解决方案3】:

    查看jsFiddle 中的代码,以及我对this SO-question 的回答

    您不能在循环中执行setTimeout。创建一个函数,并在下一个 setTimeout 中调用它:

    function changeColor() {
                document.querySelector('.style')
                 .style.backgroundColor = colors[rand(colors.length)];
                setTimeout(changeColor,1000);
    }
    

    Here's你的jsFiddle,重写

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-13
      • 2011-08-15
      • 1970-01-01
      • 1970-01-01
      • 2012-08-06
      • 2021-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多