admin管理员组文章数量:1405585
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?
2 Answers
Reset to default 5Modifying 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.
本文标签: javascriptHow can I reduce slowdowns from mousemove eventStack Overflow
版权声明:本文标题:javascript - How can I reduce slowdowns from mousemove event? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744340814a2601464.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论