正在为setTimeout创建循环

Creating a loop for setTimeout

本文关键字:创建 循环 setTimeout      更新时间:2023-09-26

我有这样的代码,它工作得很好,可以在计时器结束时创建闪烁效果,但我相信使用循环可以更容易地完成。有人能给我看那个循环吗,因为我搞不清楚,提前谢谢。

function stopTimer() {
clearTimeout(timerID);
timerID = null;
timerObj.value = save;
var theBody = document.getElementById("theBody");
setTimeout(function () { theBody.className = "white"; }, 0);
setTimeout(function () { theBody.className = "red"; }, 250);
setTimeout(function () { theBody.className = "white"; }, 500);
setTimeout(function () { theBody.className = "red"; }, 750);
setTimeout(function () { theBody.className = "white"; }, 1000);
setTimeout(function () { theBody.className = "red"; }, 1250);
setTimeout(function () { theBody.className = "white"; }, 1500);
setTimeout(function () { theBody.className = "red"; }, 1750);
setTimeout(function () { theBody.className = "white"; }, 2000);
setTimeout(function () { theBody.className = "white"; }, 2250);
setTimeout(function () { theBody.className = "red"; }, 2500);
setTimeout(function () { theBody.className = "white"; }, 2750);
setTimeout(function () { theBody.className = "red"; }, 3000);
setTimeout(function () { theBody.className = "white"; }, 3250);
setTimeout(function () { theBody.className = "red"; }, 3500);
setTimeout(function () { theBody.className = "white"; }, 3750);
setTimeout(function () { theBody.className = "red"; }, 4000);
setTimeout(function () { theBody.className = "white"; }, 4250);
var audio = document.createElement("audio");
audio.src = "alarm.mp3";
theBody.appendChild(audio);
audio.setAttribute("id", "audio");
audio.play();
setTimeout(function () {
    audio.pause();
}, 6000);``

}

这里有一个快速/肮脏的方法

function white() { theBody.className = "white"; }
function red()   { theBody.className = "red"; }
for (var i=0; i<=4250; i+=500) {
  setTimeout(white, i);
  setTimeout(red, i+250);
}

更可能的情况是,您只想使用setInterval设置一个间隔,并连续循环,直到将来发生某个事件。像

  • 循环5秒
  • 或者,循环直到用户单击stop按钮
  • 或者其他条件

您可以使用setInterval,它在每个间隔调用有问题的函数,直到取消为止。

var myVar = setInterval(function(){ 
  theBody.className = (theBody.className == "white")? "red" : "white";
}, 250);

要停止执行,您所要做的就是:

 clearInterval(myVar);

您可以使用setInterval每隔一段时间做一些事情,也可以使用clearInterval清除该间隔(使其停止)。

var theBody = document.getElementById("theBody");
var max = 10;
var effect = setInterval(function () {
    theBody.className =  (max % 2 == 0) ? "white" : "red";
    max--;
    if (max == 0) {
        clearInterval(effect);
    }
}, 
250 // how often to do this in milliseconds
);

请参阅fiddle