我想要的行为是这样的:背景颜色变为金色,并在 X 时间长度内保持该颜色。然后,背景颜色变为红色,并在 Y 时间长度内保持该颜色。然后背景颜色变回金色,并在 X 时间内保持该颜色。然后背景颜色变回红色并保持 Y 时间长度。整个套件和 caboodle 以循环方式执行 Z 次,然后结束。
我尝试将 setInterval 函数放入 for 循环中(以计算我们进行更改的次数),但发现所有已设置为 setInterval 的函数本身都开始运行间隔同时计时(不按顺序)。
我希望这是清楚的。这是我努力的 JSFiddle:http://jsfiddle.net/6WE6s/3/我已经设法让背景颜色以均匀的模式变化,但我想要上面描述的模式,但我对下一步该做什么感到困惑。
在此先感谢您的帮助! :)
最佳答案
var colors = [
['gold', 2000], // X = 2000 miliseconds
['red', 1000] // Y = 1000
],
repeat = 3, // Z = 3,
index = 0, // current position in colors array
changeColor = function( ) {
// if index == colors.length then mod = 0
var mod = index % colors.length;
if(!index || mod || --repeat ) {
index = mod;
var data = colors[ index++ ]; // data = [ currentColor, currentColorTimeout ]
document.body.style.background = data[0];
setTimeout( changeColor, data[1] ); // and so on
}
//if index >0 && index == last
//then decrement `repeat` and check if is == 0
//nothing to do :)
};
changeColor(); // run
这是一个简单的例子。您可以使用参数 (colors
,repeats
) 及其主体创建函数,如上。
注意:
setInterval
不适合这个目的,因为在 setInterval
中你传递了一次超时
如果repeat
初始为0,则重复无限次
关于javascript - 如何以稍微不规则的模式(例如在 for 循环中)使用 setInterval?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12312771/