我在寫一個bot,它以可變間隔發送警報。我正在使用setTimeout(),我有一個問題,我似乎無法弄清楚。 (簡化)的代碼是:連續調用兩次setTimeout()函數
//Original call to setTimeout():
timeout = setTimeout(issueAlarm, 2147483647); // highest possible interval setTimeout() will accept.
//In bot:
// dh is a priority queue that keeps timestamps sorted from smaller to larger as the user requests alerts.
//'mom' is a moment.js variable that holds the most recent request.
//This block of code checks the PQ and if what the user just entered is smaller than what is already stored, it updates the timeout.
//This seems to work fine
// First get input from user and store the desired time of first alert in 'mom'. Then:
var nextD = dh.peekNext();
if (nextD.timestamp >= mom.valueOf()){
var now = new Date();
clearTimeout(timeout);
timeout = mom.valueOf() - now;
setTimeout(issueAlarm, timeout);
}
//issueAlarm function:
function issueAlarm() {
var next = dh.getNext(); // this pops the first alarm from the queue
// here goes some code that issues message. Then:
var peek = dh.peekNext(); // this looks at the next element in the queue without popping it
if (peek) {
var now = new Date();
timeout = peek.timestamp - now;
setTimeout(issueAlarm, timeout);
}
}
的例子輸入信號是: 第一輸入中輸入:設置一個警報每8小時從現在開始5分鐘(「呼叫Bob」)
第二輸入輸入:設置從現在起4分鐘開始,每8小時發出一次警報(「致電簡」)
4分鐘後,我正確地獲得了「致電簡」(這一個從機器人代碼設置) 一分鐘後,我正確地得到「打電話給鮑勃「,但我也得到」致電簡「(這應該不會發生,直到8小時後)
我打印所有的超時值,他們似乎是正確的。我還打印issueAlarm()函數內的setTimeout()函數的返回值。
第一次調用內部:_idleTimeout:59994(這是正確的,下一個電話是在一分鐘內)
第二個呼叫內部:_idleTimeout:28739994(這看起來是正確的,這是約8小時,但我仍然立即解決第三個來電)
第三調用內部:_idleTimeout:28799991(此超時看起來正確的,但這個函數調用不應該發生的)
我使用botFramework。我對JavaScript和node.js的知識遠非廣泛。我印出了所有我能想到的東西,但我無法弄清楚爲什麼第三個電話正在馬上做出。
只有當輸入的第一個輸入請求的開始時間晚於在第二個輸入中輸入的開始時間時,纔會發生這種情況。但我不明白爲什麼。
將'timeout'的引用從'setTimeout'改爲'timeout = mom.valueOf() - now;'和'timeout = peek.timestamp - now;''的目的是什麼? – guest271314
在設置新的之前,您沒有清除issueAlarm中的超時,如果有問題的話。另外,您是否確定您爲超時發出的超時間隔值,它們可能比您想象的要短嗎? – Piwwoli
@Piwwoli:我已經嘗試清除超時。它沒有工作。我在這裏打印從setTimeout函數返回的間隔。正如我所說的,在將它們傳遞給函數之前,我還打印了這些值。他們是正確的 – Irene