1

I'm trying to make a div move with the mouse (game). Here is a piece of jQuery code:

var a = $('.player'); // the div i want it to move
var all = $('.container'); // this is full hight / width container (all the page)

$(all).mousemove(function (e) { // if the mouse move the div move

    $(a).animate({

        left: e.pageX

    },50)

});

it actually work but it have a lag because it detects almost 100 pageX in the second (or that what i think)

so i try to to move it once every 0.5 s to eliminate the lag :

var a = $('.player'); // the div i want it to move

var all = $('.container'); // this is full hight / width container (all the page)

$(all).mousemove(function (e) { // if the mouse move the div move

     setInterval(function(){

         $(a).animate({

             left: e.pageX       // move the div  once every 0.5 s

         },50);

    } , 500 );  

});

but it doesnt work !

S.Daineko
  • 1,790
  • 1
  • 20
  • 29
user11678472
  • 45
  • 1
  • 5
  • 2
    Hey, what you are looking for is a event throttling. Searching "js mousemove throttle" should get you the answers – Akshay May 18 '20 at 16:34

1 Answers1

0

This is because your code is creating an additional new timer interval loop on every mouse move. Those are going to pile up like crazy!

I think what you really want is to debounce or throttle your mousemove events so they only fire every 500ms. I could have sworn jQuery had this in its library, but I can't find it, so here's how you'd do it with vanilla JavaScript:

// Lodash has one of these; don't rewrite if you already have a debouncer loaded

function debounce(ms, fn) {
  let deferredCall = null;
  let timeout = null;
  return (...args) => {
    if (timeout) {
      // We're currently waiting before calling our function
      deferredCall = () => fn(...args);
    } else {
      // Run immediately
      fn(...args);

      // Don't run again until some time has passed
      timeout = setTimeout(() => {
        timeout = null;
        if (deferredCall) {
          // Call the latest deferred call
          deferredCall();
          deferredCall = null;
        }
      }, ms);
    }
  };
}

This debounce function creates a new version of a function, so you'd wrap your mouseMove function and use that in your event handler:

$(all).mousemove(
  // move the div once every 0.5 s
  debounce(500, e => { 
    $(a).animate({
      left: e.pageX
    }, 50);
  })
);
Jacob
  • 77,566
  • 24
  • 149
  • 228