javascript setInterval - 如何多次调用并保持setInterval Id?

时间:2013-10-29 10:07:14

标签: javascript jquery

我正在尝试使用下面的代码来查看是否可以将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没有被拾取,它总是试图使用第一个键停止间隔?任何想法如何才能正常工作?

3 个答案:

答案 0 :(得分:1)

您正在设置间隔之间的tepId值,因此在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);

答案 1 :(得分: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]);
    }
}

答案 2 :(得分:0)

调用timerMethod时,

tempId始终等于list[1]。您应该使用或其他变量名称,或直接列出[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)