Reputation: 19
i'm using mousemove event and as it executes each time possible, I want to optimize this and I think about these two possibilities:
ok = true;
function mousemove(e)
{
if(ok == true)
{
ok = false;
window.setTimeout(function(){ ok = true; }, 1000/60);//60 FPS
//Code here
}
}
and
lastTime = +new Date();
function mousemove(e)
{
if(+new Date() - lastTime > 1/60)//60 FPS
{
lastTime = +new Date();
//Code here
}
}
So is it better to use window interval (or timeout) or use a timestamp?
(if you have another idea, I take!)
Thank you!
Upvotes: 1
Views: 83
Reputation: 45101
Within the event I would simply update a variable (e.g. position of the mouse) and within a second event (e.g. requestAnimationFrame) I would read that variable and reset it. So in the next loop I check if it has a valid value and compute it again (cause the user moved the mouse further) or it is still not set (cause the user didn't move the mouse any further).
let currentPosition = null;
function onPaint() {
if(currentPosition !== null) {
let paintPosition = currentPosition;
currentPosition = null;
// ToDo: update visualization by using paintPosition...
}
window.requestAnimationFrame(onPaint);
}
function onMouseMove(e) {
currentPosition = e.position;
}
onPaint();
Upvotes: 1
Reputation: 10342
Using an interval means having a function that is executed 60 times per second, even if the mouse is not being used. Checking if the right period has passed within the mouse event callback is only executed when needed.
So I'd discard the interval approach (same for timeout):
(function () {
var time=+new Date();
myElement.addEventListener('mousemove', function () {
if (time- (+new Date()) < 60) return;
time=+new Date();
/* Here my logic*/
});
})()
Upvotes: 0