我正在试验下面的代码,看看我是否可以将 setInterval Id 作为唯一键的值存储在关联数组中,然后通过使用唯一值作为键来停止调用函数中的间隔,如下所示,这应该给我 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
我传递给函数的第二个没有被拾取,它总是试图使用第一个键停止间隔?知道如何使它正常工作吗?