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

247
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 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