如何让我的程序持续运行

How to make my program run continously

本文关键字:运行 程序 我的      更新时间:2023-09-26

我想让我的程序连续运行,以便在完成后它会在 2 秒后再次运行。

这是我的代码:

$(document).ready(function () {
var colorBlocks = [
    'skip',
    'yellow',
    'green',
    'blue',
    'white',
    'orange'
]
function colourBoard() {
    $.each(colorBlocks, function (i) {
        setTimeout(function() {
            $('#' + this).css("background", this);
            setTimeout(function() {
                $('#' + this).css("background", '#212121');
            }.bind(this), i * 200);
        }.bind(this), i * 500);
    });
}
colourBoard();
});
我会为此

使用setInterval()

var myVar = setInterval(myTimer, 1000);
function myTimer() {
    var d = new Date();
    document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}

您可以让函数在上次更改时调用自身。

function colourBoard() {
    $.each(colorBlocks, function (i) {
        setTimeout(function() {
            $('#' + this).css("background", this);
            setTimeout(function() {
                $('#' + this).css("background", '#212121');
                // start over if it's the last one
                if(i === colorBlocks.length-1){
                   colourBoard();
                }

            }.bind(this), i * 200);
        }.bind(this), i * 500);
    });
}
colourBoard();

优点:使用 setInterval 不会开始在功能上领先于计时器

缺点: 暂停/重新启动比使用 setInterval 需要更多的逻辑