Attemping to get a div to "follow" cursor on mousemove, but with a delay

I did it slightly differently. Instead of using setInterval (or even setTimeout) - I just made the animation take x amount of milliseconds to complete. The longer the animation, the less responsive the following div will seem to be.

The only problem I notice is that it gets backed up if the mouse is moved a lot.

$(document).ready(function () {

    $("body").mousemove(function (e) {
        handleMouseMove(e);
    });

    function handleMouseMove(event) {

        var x = event.pageX;
        var y = event.pageY;

        $("#cube").animate({
            left: x,
            top: y
        }, 1);
    }
});

https://jsfiddle.net/jvmravoz/1/


Remove SetInterval and add a $("#cube").stop(); to stop the old animation based on old (x,y) so you can start a new "faster" one.

$(document).ready(function() {
    $("body").mousemove(function (e) {
        $("#cube").stop();
        handleMouseMove(e);
    });

function handleMouseMove(event) {

  var x = event.pageX,
      y = event.pageY;

      $("#cube").animate({
        left: x,
        top: y
      }, 50);

}
});

Working example https://jsfiddle.net/jabnxgp7/