最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I reduce slowdowns from mousemove event? - Stack Overflow

programmeradmin5浏览0评论

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?

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?

Share Improve this question edited Nov 22, 2020 at 11:31 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jan 11, 2012 at 16:39 Henry MerriamHenry Merriam 8246 silver badges21 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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

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

发布评论

评论列表(0)

  1. 暂无评论