Search code examples
javascriptjqueryhtmlperformancemousemove

Get mouse moving speed


I didn't get a exact solution/calculation from stackoverflow so i created a question

var timestamp = null;
var mY = 0;
$(document).mousemove(function(e) {
    var now = Date.now();
    currentmY = e.pageY;



    mY = e.pageY;
    timestamp = now;
});

I need to get a speed value when mouse move vertical angle.

https://jsfiddle.net/58tjr9o1/


Solution

  • The speed is simply the distance divided by the time it took:

    speed = distance / time
    

    The distance is currentmY - mY, while the time is now - timestamp. So in the end, you get:

    var timestamp = 0;
    var mY = 0;
    $(document).mousemove(function(e) {
        var now = Date.now();
        var currentmY = e.screenY;
    
        var dt = now - timestamp;
        var distance = Math.abs(currentmY - mY);
        var speed = Math.round(distance / dt * 1000);
        console.log(dt, distance, speed);
        document.getElementById("speed").innerHTML = speed;
        
        mY = currentmY;
        timestamp = now;
    });
    

    Note the * 1000, since the timestamp is in milliseconds. The speed is here in pixels/second.

    See this updated fiddle.