如何减少 mousemove 事件导致的速度减慢?
我正在 mousemove
上运行一个相对简单的函数(更新 span
的 innerHTML
)。该应用程序是一个 Leaflet 地图。当鼠标移动时,缩放、平移和加载图块时会出现明显的滞后。我最多只需要每秒更新 span
大约 10-20 次。 (有关相关页面,请参阅此处;更新针对上部的 X/Z 指示器 -右角。)
延迟和/或延迟 mousemove
事件调用的最佳方法是什么?跳过更新 innerHTML
是否足够好?我可以在超时后取消注册并重新注册该事件吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
修改span的文本节点会比修改innerHTML效率高很多。
但是,如果文本节点不能满足要求,并且您需要在 mousemove 上使用 innerHTML,则可以在 mousemove 处理程序中使用阈值。
避免使用 jQuery 等;它们不必要地使事情变得更慢并且增加了更多的复杂性。
Modifying the text node of the span will be much more efficient than modifying innerHTML.
But if text nodes won't fulfill the requirement, and you need innerHTML on mousemove, you can use a threshold in the mousemove handler.
Avoid jQuery, et al; they needlessly make things a lot slower and add a lot more complexity.
让 mousemove 将
innerHTML
字符串设置为变量,并在可行的情况下在元素上使用直接纯 DOM mousemove 事件。请参阅 http://bugs.jquery.com/ticket/4398现在 mousemove 事件几乎不执行任何操作工作(顺便说一句,设置innerHTML是一项很大的工作)并且span每秒更新10次。
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/4398Now the mousemove event hardly does any work (setting innerHTML is A LOT of work btw) and the span is updated 10 times per second.