簡體   English   中英

clearTimeout無法在Node.js中的對象數組內超時

[英]clearTimeout not working for timeout inside an array of objects in Node.js

我正在使用setTimeout創建超時並將其存儲在Node.js中的以下代碼中的對象數組中:

actionSensorTimers = [];

/* -------------- OTHER CODE -----------------*/

let delay = (actionStep.delay !== undefined) ? actionStep.delay : 0;

let timeout = {
    name: name,
    timeout: setTimeout(async function() {
        url += properties.join('&');
        await request(url, function(err, res, body) {});

        let previousState = {
            ...targetIotControlPoint,
            previousState: undefined
        }

        await iotConn.query('UPDATE ' + actionStep.type + 's SET previousState = ?'
            + ' WHERE name = ?', [JSON.stringify(previousState), targetIotControlPoint.name]);
    }, delay)
}
actionSensorTimers.push(timeout);

這段代碼運行完美:延遲后成功觸發了回調,發出了請求並更新了數據庫。 但是,當我嘗試使用以下代碼取消setTimeout時,在延遲后仍然會被觸發。

let found = actionSensorTimers.find(timer => timer.name == name);
if (found !== undefined) {
    console.log(found);
    clearTimeout(found.timeout);
    actionSensorTimers = actionSensorTimers.filter(timer => timer.name != name);
}

Array.find()成功找到該對象並將該對象記錄在控制台上(請參見下圖),但是超時不會被取消。

在訪問actionSensorTimers [n] .timeout時,問題不應該在范圍內,因為Array.find()找到正確的對象並將其成功記錄。

控制台輸出

感謝您的幫助!

var t = setTimeout(function(){alert(“ Hello11​​1111111”);},5000); clearTimeout(t);它有效!

據我所知Array.prototype.find()返回值的副本我認為您使用對象的副本,您應該使用同一對象而不是副本

好的,事實證明問題出在我setTimeout代碼所在的循環中。我將兩個超時對象以相同的名稱值但超時時間推送到數組中。 這導致我的查找系統向我返回名稱匹配的數組中的FIRST元素。

由於我想取消的超時是第二個超時,因此我從來沒有獲得正確的引用,並且一直試圖取消已經運行的錯誤超時。 (在圖像中看到它說_called: true

現在,我添加了一項檢查,以防止兩個具有相同名稱參數的計時器進入我的對象數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM