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

248
Visualizações
How to make a static variable in JavaScript like we do in c ? ( to avoid re-initialization of the variable)

I watched this video on https://www.youtube.com/watch?v=cjIswDCKgu0&t=429s YouTube;

I just wanted to make a simple debounce function. but this code does not work on my device as intended. Please help.


let debounceTimes = 0;

// this code does not work as intended
let timeout; // if I make it global it works just fine
// but I don't want to do that for obvious reasons
function debounce(cb, delay = 100) {
  //  let timeout; // this is being reinitialized

  // only if I could do something like this
  // static timeout;
  // to avoid re-initializing the variable
  // return (...args) => {
  clearTimeout(timeout);
  timeout = setTimeout(() => {
    cb();
  }, delay);
  // }
}

window.addEventListener("mousemove", () => {
 // console.log("hello");
 // document.getElementById("debounce").innerText++;
  debounce(
    () => {
      debounceTimes++;
      document.getElementById("debounce").innerText = String(debounceTimes);
  }, 100);
});
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

In this example, it is not possible, since when the event is triggered it just runs the debounce function which creates the variable inside. To avoid re-initializing the variable you can:

  1. Create variable in the global scope

  2. Create another function that returns the debounce function(so the timeout is hidden in function scope)

let debounceTimes = 0;

function getDebounce() {
  let timeout;

  function debounce(cb, delay = 100) {
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      cb();
    }, delay);
  }
  return debounce;
}
const debounce = getDebounce();

window.addEventListener('mousemove', () => {
  debounce(() => {
    debounceTimes++;
    document.getElementById('debounce').innerText = String(debounceTimes);
  }, 100);
});

about 4 years ago · Juan Pablo Isaza Relatório

0

A good pattern in JS when you want a variable to be private to a function, but yet outside its scope, is to use closures and IIFE:

const debounce = (function() {
  let debounceTimes = 0;
  let timeout; // if I make it global it works just fine
  // but I don't want to do that for obvious reasons
  return (cb, delay = 100) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      cb();
      console.log("Count:", debounceTimes)
      debounceTimes++
    }, delay);
  }
})()

window.onmousemove = () => debounce(() => console.log("Debounced"),200)

about 4 years ago · Juan Pablo Isaza Relatório

0

I ended up making a class with static method and variables since it was similar to the c++ ways of doing things. but I like @Tomasz Staszkiewicz 's answer better. He made another function inside the function to achieve this.

class ignoreInput {
    static #timeout;
    static debounce (cb, delay = 100) {
        clearTimeout(this.timeout);
        this.timeout = setTimeout(() => {
            cb();
        }
        , delay);
    }

    static throttle (cb, delay = 100) {
        // some code
    }    
};
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