我遇到Javascript計時器問題。基本上,我有這2個頁面元素:無法清除計時器數組中的計時器
<input type="checkbox" id="chk" />
<input type="button id="clearAll" value="Clear Timers" />
以及管理他們下面的JavaScript:
// store all page timers here
var timers = new Array();
// clears all page timers
function clearTimers() {
console.log("Clearing all timers.")
for (var i = 0; i< timers.length; i++)
clearTimeout (timers[i]);
}
// does stuff
function foo (whichTimer, interval) {
console.log("I am timer " + whichTimer + " running once every " + interval);
}
// document load
$(document).ready(function() {
$("#clearAll").click(clearTimers);
// check status at document load
if ($("input#chk").is(':checked'))
{
console.log("Input checked at start. Creating refresh.")
t1 = setInterval("foo(1, 2000)", 2000);
timers.push(t1); // add our timer to array
console.log("Index of t1 is: " + timers.indexOf(t1));
}
else
{
console.log("Input not checked at start.");
clearTimeout(t1); //optional
}
// refresh toggle click handler
$("input#chk").click(function() {
if ($(this).is(':checked'))
{
console.log("Input got checked.");
if (!t1) {
console.log("We don't have a t1 yet. Creating.")
t1 = setInterval("foo(1, 2000)", 2000);
timers.push(t1); // add our timer to array
console.log("Index of t1 is: " + timers.indexOf(t1));
}
else {
console.log("t1 already exists and is clear. Setting new timeout.");
t1 = setInterval("foo(1,2000)", 2000);
console.log("Index of t1 is: " + timers.indexOf(t1));
}
}
else
{
console.log ("Input got unchecked. Clearing t1.");
clearTimeout(t1);
console.log("Index of t1 is: " + timers.indexOf(t1));
}
});
}
我有一個網頁,其內容是動態變化的(包括主網頁內容),所以任何老前輩在更改內容時必須取消。所以我去了老式的計時器陣列技巧來做到這一點。
該示例顯示了一個複選框,用於切換頁面的自動刷新,並且在獨立使用時似乎可以正常工作。
我唯一的問題是,一旦更新是有效的(即t1
有效果setInterval
),該clearTimers()
功能無法停止活動定時器。
這裏是一個樣本控制檯輸出,看看我說的是:
Input not checked at start.
Input got checked.
We don't have a t1 yet. Creating.
Index of t1 is: 0
I am timer 1 running once every 2000
I am timer 1 running once every 2000
Input got unchecked. Clearing t1.
Index of t1 is: 0
Input got checked.
t1 already exists and is clear. Setting new timeout.
Index of t1 is: 0
I am timer 1 running once every 2000
I am timer 1 running once every 2000
Input got unchecked. Clearing t1.
Index of t1 is: -1 <--------------- This is what starts to worry me
Input got checked.
t1 already exists and is clear. Setting new timeout.
Index of t1 is: -1
I am timer 1 running once every 2000
I am timer 1 running once every 2000
I am timer 1 running once every 2000
Clearing all timers.
I am timer 1 running once every 2000
I am timer 1 running once every 2000
I am timer 1 running once every 2000
I am timer 1 running once every 2000
Input got unchecked. Clearing t1. <------- Need to uncheck the box to stop the timer
Index of t1 is: -1
還要注意如何Array.indexOf(t1)
第一返回0,然後-1相同的一組操作後。這就是說:
問題1:爲什麼會發生這種情況?
問題2:我能爲我的代碼正常工作做些什麼?
你的代碼是充滿了語法和引用錯誤。 – Shmiddty