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

189
Vistas
Javascript debounce for mousemove event not working

I checked SO and found this answer link and wrote my solution link , but in reality it doesn't work.

Task:

  1. Writing multiple blocks and adding a mouseover event listener to them.
  2. After the event is fired, it will be processed with a debounce.
  3. Displaying an event in the console

My сode:

const cards = document.getElementsByClassName('card-wrapper');

function onMouseMoveHandler(e) {
  return debounce(() => update(e));
}

function debounce(func) {
  let isCan = true;
  
  return () => {
    if (isCan) {
      func();
      isCan = false;
      setTimeout(() => isCan = true, 500);
    }
   }
}

function update(e) {
  console.log(e);
}

for (let i = 0; i < cards.length; i++) {
  cards[i].onmousemove = onMouseMoveHandler;
}
body {
  display: flex;
}

.card-wrapper {
  margin: 2%;
  width: 300px;
  height: 150px;
}
.card {
  width: 100%;
  height: 100%;
  background: blue;
}
<div class="card-wrapper card-1">
  <div class="card"></div>
</div>

<div class="card-wrapper card-2">
  <div class="card"></div>
</div>

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

0

You wrapped onMouseMoveHandler in a function which prevents the debounced function from getting called. While you could do debounce(...)() to call it that won't be the behaviour you desire. Instead, you should make it a plain variable and assign it to the debounced function return from debounce.

// no need for a function!
const onMouseMoveHandler = debounce((e) => update(e)); // or just debounce(update);

function debounce(func) {
  let isCan = true;
  
  return () => {
    if (isCan) {
      func();
      isCan = false;
      setTimeout(() => isCan = true, 500);
    }
   }
}

function update(e) {
  console.log(e);
}

for (let i = 0; i < cards.length; i++) {
  cards[i].onmousemove = onMouseMoveHandler;
}
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