最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to make an infinite loop with delay in JavaScript? - Stack Overflow

programmeradmin0浏览0评论

I'm trying to make div which could change it color. Here is my code:

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>

I'm trying to make div which could change it color. Here is my code:

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>

But I can't find out why it doesn't work.
EDIT: the script also crashes the browser

Share Improve this question edited Mar 31, 2020 at 19:00 Marco Bonelli 69.3k21 gold badges126 silver badges145 bronze badges asked Oct 19, 2014 at 14:16 barbarabarbara 3,2018 gold badges32 silver badges58 bronze badges 5
  • 1 Add your code here as well. There is a reason you can't include a jsfiddle link without any code here. – Sirko Commented Oct 19, 2014 at 14:17
  • 1 terrible formatting for someone with more than 100 rep.. – DividedByZero Commented Oct 19, 2014 at 14:18
  • developer.mozilla.org/en-US/docs/Web/API/… – vittore Commented Oct 19, 2014 at 14:18
  • You have an infinite loop, that's why. The setTimeout callback can never be executed because the event loop can't proceed the next tick. – Felix Kling Commented Oct 19, 2014 at 14:20
  • @FelixKling Actually it's not an infinite loop, but filling the task queue endlessly with new setTimeout tasks I'd say. The reason the browser crashes is simply a stack overflow. – KooiInc Commented Oct 19, 2014 at 14:39
Add a comment  | 

3 Answers 3

Reset to default 12

Single element

Assuming that your markup is this:

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

To create a "color loop" you'll have to use setInterva() to set a function that will be executed infinite times (with a defined interval) to change the color. Here is the correct code:

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

This will change the color every 2 seconds. If you want to stop it, you can use the clearInterval() function:

clearInterval(myInterval);

Multiple elements

Assuming your markup is:

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

You can use the getElementsByClassName() method instead:

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

Working example

Here's a working example with multiple elements:

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>

You need setInterval function.

Also, instead of style, you need .style selector (the class selector). If you are using jquery, you may use $(".style") instead of 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>

See the code in this jsFiddle, and my answer to this SO-question

You can't execute setTimeout in a loop. Create a function, and call it in a next setTimeout:

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

Here's your jsFiddle, rewritten

发布评论

评论列表(0)

  1. 暂无评论