我正在試驗下面的代碼,看我是否可以將setInterval Id作爲唯一鍵的值存儲在關聯數組中,然後通過使用唯一值作爲鍵來停止被調用函數中的時間間隔它的setInterval的ID作爲值:javascript setInterval - 如何調用多次並保持setInterval ID?
//random unique values to be used as key
var list = [];
for (var i = 0; i < 10; i++) {
uniqueID = Math.floor(Math.random() * 90000) + 10000;
list[i] = uniqueID;
}
//function that gets called by interval
var runCount = 0;
function timerMethod(id) {
runCount++;
if (runCount > 3) {
console.log('done with interval where key was ' + id + ' and value was ' + id_array[id]);
clearInterval(id_array[id]);
}
}
//stores the key => setIntervalId combo
var id_array = {};
//fire the interval
var tempId = list[0];
id_array[tempId] = setInterval(function() {
timerMethod(tempId);
}, 3000);
//fire the second bast*rd
var tempId = list[1];
id_array[tempId] = setInterval(function() {
timerMethod(tempId);
}, 3000);
的代碼不工作 - 不知何故第二tempId
我傳遞給函數沒有得到回升,並總是試圖用第一停止區間鍵?任何想法如何可以使工作正常?