Node.js – timeout-ref() & timeout-unref() 方法
Timeout 物件是內部建立的,並由 setTimeout() 和 setInterval() 方法返回。如果要取消計劃的操作,可以使用此物件並將其傳遞給 clearTimeout() 或 clearInterval()。
以下是可用於控制預設行為的 timeout 類 ref 物件:
1. timeout.ref()
如果 timeout 物件的事件迴圈不存在,則呼叫此方法。此方法的實際用途僅在呼叫 timeout.unref() 後,並且需要再次引用 timeout 物件時。
語法
timeout.ref()
2. timeout.unref()
此方法將告訴 timeout 物件 Node.js 事件迴圈不再需要處於活動狀態。如果沒有其他活動或正在執行的程序,則在呼叫 Timeout 物件的回撥之前,程序可能會退出。
語法
timeout.unref()
示例
建立一個名為“timeout.js”的檔案並複製以下程式碼。建立檔案後,使用命令“node timeout.js”執行此程式碼,如下例所示。
// Timeout class Demo Example
// Setting the Timeout using setTimeout() Method
var Timeout = setTimeout(function fun() {
console.log("1. Setting Timeout for 100ms", 100);
});
// Checking if the timeout.hasRef() object
console.log("2. ", Timeout.hasRef();
// Printing the Timeout ref
console.log("3. ", Timeout.ref());
// Unreferencing and referencing again
console.log("4. ", Timeout.unref());
// Checking if the reference is removed ?
console.log("5. ", Timeout.hasRef());
Timeout.ref()
// Refreshing the timer
console.log("6. ", Timeout.hasRef());
// Clears setInterval Timeout
clearTimeout(Timeout);
console.log("7. Timeout is cleared !");輸出
它將產生以下輸出:
2. true
3. Timeout {
_called: false,
_idleTimeout: 1,
_idlePrev: [TimersList],
_idleNext: [TimersList],
_idleStart: 358,
_onTimeout: [Function: fun],
_timerArgs: undefined,
_repeat: null,
_destroyed: false,
[Symbol(unrefed)]: false,
[Symbol(asyncId)]: 5,
[Symbol(triggerId)]: 1 }
4. Timeout {
_called: false,
_idleTimeout: 1,
_idlePrev: null,
_idleNext: null,
_idleStart: 358,
_onTimeout: [Function: fun],
_timerArgs: undefined,
_repeat: null,
_destroyed: false,
_handle: [Timer],
[Symbol(unrefed)]: false,
[Symbol(asyncId)]: 5,
[Symbol(triggerId)]: 1 }
5. false
6. true
7. Timeout is cleared !
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP