我有两对功能。这些功能需要运行9次,持续3秒(时间长度)。每次运行之间的延迟应为1秒。
有没有更好的方法来缩短loopIT()函数?
window.onload = function () {
// Get the button that will trigger the action
var b = document.getElementById('trigger');
// and set the onclick handler here instead of in HTML
b.onclick = loopIT;
function startIT() {
// close switch, turn the light on.
}
function stopIT() {
// open switch, turn the light off.
}
function loopIT() {
// Lights on, wait 3 seconds, turn lights off. #1
setTimeout(startIT, 100);
setTimeout(stopIT, 3100);
// Lights on, wait 3 seconds, turn lights off. #2
setTimeout(startIT, 4100);
setTimeout(stopIT, 7100);
// Lights on, wait 3 seconds, turn lights off. #3
setTimeout(startIT, 8100);
setTimeout(stopIT, 11100);
// Lights on, wait 3 seconds, turn lights off. #4
setTimeout(startIT, 12100);
setTimeout(stopIT, 15100);
// Lights on, wait 3 seconds, turn lights off. #4
setTimeout(startIT, 16100);
setTimeout(stopIT, 19100);
// Lights on, wait 3 seconds, turn lights off. #5
setTimeout(startIT, 22100);
setTimeout(stopIT, 25100);
// Lights on, wait 3 seconds, turn lights off. #6
setTimeout(startIT, 26100);
setTimeout(stopIT, 29100);
// Lights on, wait 3 seconds, turn lights off. #7
setTimeout(startIT, 30100);
setTimeout(stopIT, 33100);
// Lights on, wait 3 seconds, turn lights off. #8
setTimeout(startIT, 34100);
setTimeout(stopIT, 37100);
// Lights on, wait 3 seconds, turn lights off. #9
}
}
答案 0 :(得分:0)
你可以使用两个for循环。
function loopIT() {
// goes from #1 to #4 (inclusive)
for (var i = 4000; i <= 16000; i += 4000) {
setTimeout(startIT, i + 100);
setTimeout(stopIT, i + 3100);
}
// goes from #5 to #9 (inclusive)
for (var j = 22000; j <= 34000; j += 4000) {
setTimeout(startIT, j + 100);
setTimeout(stopIT, j + 3100);
}
}
答案 1 :(得分:0)
您可以使用setInterval
,它将每N毫秒运行一次某个功能。
您可以使用计数器在N次后停止。
// count the number of times we turned the lights on
var cpt = 0;
// turn the lights on right away
lightsOn();
// turn the lights on every 3 seconds
var intervalOn = setInterval(lightsOn, 3000);
function lightsOn()
{
console.log("lights on");
// Turn the lights off in 1 second
setTimeout(lightsOff, 1000);
}
function lightsOff()
{
console.log("lights off");
++cpt;
// If we've turned off the lights 9 times, stop turning the lights on.
if (cpt == 9)
{
clearInterval(intervalOn);
}
}
&#13;
答案 2 :(得分:0)
我建议使用do-while循环,直到你到达终点(在你的情况下大约40s)。您还可以添加每个循环增加一次的迭代器。
function loopIt() {
let timeout = 100;
do {
setTimeout(startIt(), timeout);
timeout += 3000;
setTimeout(stopIt(), timeout);
timeout += 1000;
} while (timeout < 40000);
}
答案 3 :(得分:0)
我的建议是:
var repeatedTimes = 0;
function loopIt(){
if(repeatedTimes < 9){
startIT();
setTimeout(stopIT, 3000);
setTimeout(loopIt, 4000);
}
repeatedTimes++;
}
setTimeout(loopIt, 100);
希望有所帮助