正在为setTimeout创建循环
Creating a loop for setTimeout
我有这样的代码,它工作得很好,可以在计时器结束时创建闪烁效果,但我相信使用循环可以更容易地完成。有人能给我看那个循环吗,因为我搞不清楚,提前谢谢。
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
相关文章:
- 创建一个循环来简化HTML和CSS代码
- 正在为循环创建唯一id
- 使用来自不同循环Javascript的数据创建数组
- 在for循环中仅创建手风琴的内容
- 在Django中,可以在视图中创建一个包含js的变量,然后在循环模板标记中使用它
- 循环选择标记并创建数组或字符串
- jQuery使用animate创建循环
- 反应.js通过数组创建循环
- 这是否在javascript中创建循环引用
- 为什么要创建循环来获取事件的元素
- 创建循环设置超时 jquery 数组
- jQuery basic:如何使用此结构创建循环
- Javascript:创建循环以连接选中复选框的结果
- 如何基于分隔符从字符串创建循环
- 如何使用two.js创建循环热点
- 正在为setTimeout创建循环
- 在Jquery中使用小数创建循环
- 如何用javascript在carousel中创建循环
- 在 javasctipt 警报或提示中创建循环
- 简单 HTML 表单创建循环中的永恒循环