0

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>
  • Why are you returning a function from your `debounce` function? `return () => {` – bloodyKnuckles May 06 '22 at 14:09
  • ... because `debounce` / `throttle` take a function as an argument and return a modified version (here a debounced respectively throttled behavior) of that function. – Peter Seliger May 06 '22 at 14:53

1 Answers1

1

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;
}
kelsny
  • 23,009
  • 3
  • 19
  • 48