Home > front end >  Is there a better way to change the timeout in javascript?
Is there a better way to change the timeout in javascript?

Time:04-25

Right Now I'm using this function to update some timeouts without having to pass the callbacks.

private _changeTimeout(timeout: NodeJS.Timeout, at: milliseconds): NodeJS.Timeout {
    // @ts-expect-error
    const timeout = setTimeout(timeout._onTimeout, at);
    clearTimeout(timeout);
    return timeout;
    }

Is there a better way, without having to use a private variable that forces me to use // @ts-expect-error?

CodePudding user response:

Yes: Create your own wrapper for setTimeout so you don't have to use undocumented internal properties of the Timeout class. Using undocumented internal properties is always going to be a maintenance hazard.

Something vaguely like:

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;
    }
}

Usage:

const t = new MyTimeout(() => {
    // ...
}, 1000);
// ...
t.change(2000);

Playground link

That might be slightly overkill, but you get the idea.

  • Related