Reputation: 824
I'm running a relatively simple function (update a span
's innerHTML
) on mousemove
. The application is a Leaflet map. When the mouse is moving, there is palpable lag when zooming, panning and loading tiles. I only need to update the span
about 10-20 times per second at most. (See here for the page in question; the update is for the X/Z indicator in the upper-right corner.)
What's the best way to delay and/or defer mousemove
event calls? Is it good enough to skip updating innerHTML
? Can I unregister and re-register the event after a timeout?
Upvotes: 3
Views: 5447
Reputation: 3023
Modifying the text node of the span will be much more efficient than modifying innerHTML.
function mouseMoveAction(ev) {
span.firstChild.data = new Date.toString();
}
But if text nodes won't fulfill the requirement, and you need innerHTML on mousemove, you can use a threshold in the mousemove handler.
/* Keep CPUs to a minimum. */
var MOUSE_MOVE_THRESHOLD = 25,
lastMouseMoveTime = -1;
function mousemoveCallback(ev) {
var now = +new Date;
if(now - lastMouseMoveTime < MOUSE_MOVE_THRESHOLD)
return;
lastMouseMoveTime = now;
mouseMoveAction(ev);
}
Avoid jQuery, et al; they needlessly make things a lot slower and add a lot more complexity.
Upvotes: 5
Reputation: 140230
Have the mousemove set the innerHTML
string to a variable and also use a direct plain DOM mousemove event on the element if feasible. See http://bugs.jquery.com/ticket/4398
!function () {
var buffer = null;
elem.onmousemove = function () {
buffer = value;
};
!function k() {
if (buffer) {
span.innerHTML = buffer;
buffer = null;
}
setTimeout(k, 100);
}();
}();
Now the mousemove event hardly does any work (setting innerHTML is A LOT of work btw) and the span is updated 10 times per second.
Upvotes: 1