Search code examples
javascriptevent-handlingsettimeoutthrottling

console.log the mouse coordinates every 2 seconds


I have the below code:

window.addEventListener('mousemove', ()=>{
   myInterval = setTimeout(mouseMove, 2000);
});

const mouseMove = () => {
    console.log('first console');
    onMouseMove = (e) => console.log("mouse location:", e.x, e.y)
}

Only at the end of the timeout I should console.log the coordinates of the mouse; however, onMouseMove is not respecting the timeout logic.

The console.log('first console') is triggered only at the end of the 2 seconds, but onMouseMove triggers with every move of the mouse.

In addition to the above, I would like to console.log only the last coordinate at the end of this 2 seconds.

I've tried changing between setInterval and setTimeout, also clearing these interval and timeout, but still didnt work as intended.


Solution

  • You want to throttle the call. There is many ways to do it, but here is a basic one where you call the function with the timeout. You set the timeout to determine if the timer is running. If it is you do not create a timeout.

    const throttleMouseMove = (callback) => {
      const ms = 2000;
    
      let active = null;
      let x = -1;
      let y = -1;
      
      return function(evt) {
        x = evt.clientX;
        y = evt.clientY;
        if (!active) {
          active = setTimeout(() => {
            callback.apply(this, [{ x, y}] );
            active = null;
          }, ms)
        }
      }
    }
    
    const sayPosition = ({ x,y }) => {
      console.log(x,y);
    }
    
    window.addEventListener('mousemove', throttleMouseMove(sayPosition));