• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Pruebas Online
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

128
Vistas
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?

almost 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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.

almost 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda