0

I would like to call a function when mousemove ends.

I have an onmousemove event listener like below which fires too many times:

window.onmousemove = (e) => { console.log(e) }

I would like to reduce calling the function too often to prevent high load.

For example, call the function once when the cursor stops.

If the are any other solutions I will be glad to try them as well.

Systems Rebooter
  • 1,281
  • 2
  • 14
  • 30
  • 1
    Does this answer your question? [How to detect when mousemove has stopped](https://stackoverflow.com/questions/15066849/how-to-detect-when-mousemove-has-stopped) – angel.bonev Mar 01 '21 at 12:59

2 Answers2

1

There is no way of directly doing it. But you could try this:

var timeout;
element.onmousemove = function (e) {
    if (timeout) clearTimeout(timeout);
    timeout = setTimeout(function() {
        // do your stuff here
    }, 200);
}

It will fire if there is no event detected for 200 milliseconds.

blaumeise20
  • 2,148
  • 8
  • 26
1

You can wrap your event callback in a debounce function. This wrapping function will only get called if you stop for 1/4 of a second after you start moving the mouse. If you start moving within 250 milliseconds after stopping, the timeout will reset and wait till you stop again.

const debounce = function(func, wait, immediate) {
  let timeout;
  return function() {
    const
      context = this,
      args = arguments,
      later = function() {
        timeout = null;
        if (!immediate) func.apply(context, args);
      },
      callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) func.apply(context, args);
  };
};

const onMouseMove = (e) => {
  console.log(`Stopped position: (${e.clientX}, ${e.clientY})`);
};

const debounceMouseMove = debounce(onMouseMove, 250); // 1/4 of a second

document.addEventListener('mousemove', debounceMouseMove);
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132