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

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

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