Skip to content
Advertisement

How can I reduce slowdowns from mousemove event?

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement