How can I reduce slowdowns from mousemove event?

ぃ、小莉子 提交于 2019-12-10 11:41:31

问题


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?


回答1:


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.




回答2:


Modify 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 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.



来源:https://stackoverflow.com/questions/8823041/how-can-i-reduce-slowdowns-from-mousemove-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!