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