0

我正在试验下面的代码,看看我是否可以将 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我传递给函数的第二个没有被拾取,它总是试图使用第一个键停止间隔?知道如何使它正常工作吗?

4

3 回答 3

2

您在间隔之间设置 tempId 的值,因此在timerMethod函数中它一直在引用新值。这似乎按预期工作:

//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
id_array[list[0]] = setInterval(function () {
    timerMethod(list[0]);
}, 3000);


//fire the second interval
id_array[list[1]] = setInterval(function () {
    timerMethod(list[1]);
}, 3000);
于 2013-10-29T10:13:09.447 回答
0

你必须重新初始化你的runcount var喜欢,

function timerMethod(id) {
    runCount++;
    if (runCount > 3) {
        console.log('done with interval where key was ' + id + ' and value was ' + id_array[id]);
        runCount = 0;// reinit for next list
        clearInterval(id_array[id]);
    }
}
于 2013-10-29T10:13:18.160 回答
0

tempId总是等于list[1]调用 timerMethod 的时间。您应该使用或其他变量名,或直接使用 list[1]

id_array[list[1]] = setInterval(function () {
        timerMethod(list[1]);
}, 3000);

另一种方法,如果不可能使用list[i],是:

id_array[tempId] = setInterval((function (tid) {
        return function() {
             timerMethod(tid);
        }
})(tempId), 3000)
于 2013-10-29T10:16:27.590 回答