Just because it's not mouse speed. What you think now is how far the mouse moved in the x direction. This is called distance.
The inaccuracy you are experiencing may be due to ignoring the y-direction and the inaccuracy of setTimeout - using Date timestamps.
In addition, you create a cascade of mousemove handlers (which is not only wrong, but also poorly efficient). At each event (and they are quite common!) You wait 0.1 s, and then add a new listener that will be displayed at each event, and then how far the mouse moved from the first event. Another problem is that you call the mouse_coors function with a value of 0 when you click the mouse, but the mouse is unlikely to be there.
Better: save current mouse coordinates globally. Each time you update them, calculate the difference and divide it by the time elapsed since the last update. Then record the speed.
function makeVelocityCalculator(e_init, callback) { var x = e_init.clientX, y = e_init.clientY, t = Date.now(); return function(e) { var new_x = e.clientX, new_y = e.clientY, new_t = Date.now(); var x_dist = new_x - x, y_dist = new_y - y, interval = new_t - t; var velocity = Math.sqrt(x_dist*x_dist+y_dist*y_dist)/interval; callback(velocity); // update values: x = new_x; y = new_y; t = new_t; }; } $(document).ready(function() { $('#testbox').on("mousedown", function(e) { var log = makeVelocityCalculator(e, function(v) { console.log(v+"pixel/ms"); }); $(document).on("mousemove", log).one("mouseup", function(){ $(document).off("mousemove", log); }); }); });
updated violin
Bergi source share