Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

178
Views
Is there a better way to change the timeout in javascript?

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!