2013-10-29 67 views
0

我正在試驗下面的代碼,看我是否可以將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我傳遞給函數沒有得到回升,並總是試圖用第一停止區間鍵?任何想法如何可以使工作正常?

回答

1

您正在將tempId的值設置在間隔之間,因此它在所有時間都參考新值的timerMethod函數中。 這似乎按預期方式工作:當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); 
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]); 
    } 
} 
0

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)