Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

72
Vistas
debounce closure shared by two functions

i am implementing debounce function. and i was able to successfully write the function then a confusing thought came to mind.

    function debounce(fn, timeout) {
        let timeoutRef;
        return function (...args) {
            const context = this;
            function cb() {
                fn.apply(context, args);
            }
            clearTimeout(timeoutRef);
            timeoutRef = setTimeout(cb, timeout);
        };
    }
    
    function foo() {
        console.log('foo is called');
    }
    function bar() {
        console.log('bar is called');
    }
    const debouncedFoo = debounce(foo, 10000);
    const debouncedBar = debounce(bar, 2000);
    
    debouncedFoo();  
    debouncedBar();

in the above code, don't debouncedFoo and debouncedBar share same colsure variable timeoutRef ?

if that's the case when debouncedFoo() it assigns setTimeout call reference to timeoutRef variable. And later when debouncedBar() called previous timeoutRef set by debouncedFoo() call should be be cleared and new setTimeout call reference should be assigned.

in conclusion,

expected result:

bar is called

actual result:

foo is called
bar is called 

can someone please help me understand this ?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

in the above code, don't debouncedFoo and debouncedBar share same closure variable timeoutRef ?

No they not sharing the same closure. in fact function parameters "fn" and "timeout" are also bounded in closure scope it means there are there parameter which is bounded in closure scope

  1. fn
  2. timeout
  3. timeoutRef

and because you are calling debounce function 2 times so every caller have their own local stack and local closure. another thing which is important is clearTimeout(timeoutRef); here timeoutRef value is undefined so it will not work

about 4 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 Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda