Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

191
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!