Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

76
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda