I want to know the instant speed of the mouse in my update()
function.
But here's my problem: when fps
is high (>30), update()
is sometimes triggered twice between two onmousemove
events. And so, even if the mouse is moving, it's considered still for a moment.
I think this is about the relation between setInterval()
and the onmousemove
event. So here is the code that matters :
var fps = 60;
setInterval(update,1000/fps);
function update() {
console.log('update');
}
document.onmousemove = function(){
console.log('mouse');
}
It displays "update"
60 times a second, and "mouse"
each time the onmousemove
event triggers.
When the mouse is still, it goes : "update"
"update"
"update"
"update"
...
When the mouse moves, it is : "update"
"mouse"
"update"
"mouse"
...
But sometimes : "update"
"mouse"
"update"
"update"
"mouse"
...
And that's bullshit because the mouse IS moving.
So I tried different mouse movements, to see if there was a pattern, but no: circles, loops, straight lines... I also tried another mouse, but it's not a hardware problem.
I've found a partial solution. With a counter++
at each update()
, and counter=0
when onmousemove
, it allows me to skip the second update()
of a sequence of updates. But it's not perfect because sometimes there are 3 or 4 update()
in a row.
.
Is it solvable ? How to be SURE there is one and only one update()
between 2 onmousemove
?
PS 1: The more fps
, the more update()
called between two events.
PS 2: It's fine if onmousemove
is triggered several times between two update()
.
PS 3: I tried with document.addEventListener('mousemove')
, it's the same.
PS 4: I'm on a mac