[英]setInterval not repeating
我试图每4秒更改一次背景,但它会直接跳至第二种情况,并且不再更改。 为什么会这样呢?
var time = 1;
var func = function () {
'use strict';
if (time === 1) {
document.getElementById("top-background").style.backgroundColor = "#000";
time += 1;
}
if (time === 2) {
document.getElementById("top-background").style.backgroundColor = "#aaa";
time += 1;
}
if (time === 3) {
document.getElementById("top-background").style.backgroundColor = "#d5d5d5";
time -= 2;
}
};
setInterval(func, 4000);
尝试使用else if
var func = function () {
'use strict';
if (time === 1) {
document.getElementById("top-background").style.backgroundColor = "#000";
time += 1;
}
else if (time === 2) {
document.getElementById("top-background").style.backgroundColor = "#aaa";
time += 1;
}
else if (time === 3) {
document.getElementById("top-background").style.backgroundColor = "#d5d5d5";
time -= 2;
}
};
当时间等于1时,您将1加时间。 这使时间等于2。在那之后,您检查时间是否等于2,即是! 这使您继续向上直到到达时间等于3的点,然后再次将其重置为1。
您只需要一种方法来检查一个条件。 您可以使用if和elseifs来做到这一点:
if (time == 1) {
// Code...
} else if (time == 2) {
// Code...
} else {
// Code...
// Because it's not equal to 1 or 2, it must be 3.
}
或者,您也可以使用Javascript的Switch语句。
switch(time) {
case 1:
// Code...
break;
case 2:
// Code...
break;
case 3:
// Code...
break;
default:
// Something went wrong and it's not 1, 2, or 3
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.