Intervals就像重新安排自己的超时(其中differs从超时开始新的超时)。由于时间间隔重新安排,只能创建一个。 (或者说,只多达真的有必要。)
与原来职位的问题是,它是创造区间(因为它们是在循环中创建),然后只保留间隔ID(在counter
)创建的最后时间间隔!因此,clearInterval
只能停在最近的时间间隔和其他4个间隔保持运行,运行和运行..
这里是一些清理代码注释,并没有最初的问题:
var count = 5;
// only need ONE interval
var counter = setInterval(timer, 1000);
// so we do one count RIGHT NOW
timer();
function timer() {
// display first, so we start at 5: 5, 4 .. 1
console.log(count);
count--;
if (count < 0) {
// to repeat the count, comment out the clearInterval
// and do `count = 5;` or similar .. take it from here :D
clearInterval(counter);
}
}
创建单独的“状态“,可以创建一个新的倒计时对象,该对象在属性中保持状态或use a closure。这是一个封闭的例子。我还添加了一个回调函数的支持,表现出这样的功能如何可以更通用:
function makeCountdown(startCount, delay, fn) {
fn = fn || function (i) {
// default action, if fn not specified
console.log(i);
};
// local variables
var count = startCount;
var counter = setInterval(timer, delay);
timer();
function timer() {
// now count and counter refer to variables in the closure (keyword!)
// which are different each time makeCountdown is called.
fn(count);
count--;
if (count < 0) {
clearInterval(counter);
}
}
}
makeCountdown(20, 500); // uses default function
makeCountdown(10, 1000, function (i) { console.log(10 - i) });
makeCountdown(5, 2000, function (i) { console.log("SLOW! " + i) });
练习:
- 添加时倒计时“完成”,这样的回调函数倒计时可以连续运行。
- 消耗一系列生成器并使用它生成下一个
count
值。
- 已有
makeCountdown
返回可用于控制倒数的对象。
- 玩得开心!
不要创建5个区间。创建一个(没有循环)。 – user2246674 2013-05-14 05:45:33
为什么不使用'setTimeout'? – akonsu 2013-05-14 05:46:52
@ user2246674这是什么意思? – akonsu 2013-05-14 05:47:33