現在我正在使用這個函式來更新一些超時,而不必傳遞回呼。
private _changeTimeout(timeout: NodeJS.Timeout, at: milliseconds): NodeJS.Timeout {
// @ts-expect-error
const timeout = setTimeout(timeout._onTimeout, at);
clearTimeout(timeout);
return timeout;
}
有沒有更好的方法,而不必使用強制我使用的私有變數// @ts-expect-error?
uj5u.com熱心網友回復:
是的:創建您自己的包裝器,setTimeout這樣您就不必使用Timeout類的未記錄的內部屬性。使用未記錄的內部屬性總是存在維護風險。
有點像:
class MyTimeout {
private timeout: NodeJS.Timeout | null = null;
constructor(
private callback: (...args: any[]) => void,
public ms: number,
paused?: boolean,
) {
if (!paused) {
this.set();
}
}
set(ms?: number) {
if (typeof ms !== "undefined") {
this.ms = ms;
}
this.timeout = setTimeout((...args) => {
this.callback(...args);
this.timeout = null;
}, this.ms);
}
clear() {
if (this.timeout) {
clearTimeout(this.timeout);
this.timeout = null;
}
}
change(ms: number) {
const running = this.isRunning();
this.clear();
this.ms = ms;
if (running) {
this.set(ms);
}
}
get isRunning() {
return this.timeout !== null;
}
}
用法:
const t = new MyTimeout(() => {
// ...
}, 1000);
// ...
t.change(2000);
游樂場鏈接
這可能有點矯枉過正,但你明白了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/463747.html
標籤:javascript 节点.js 打字稿 设置超时
