[英]Javascript mousemove event queue
In Javascript, is it possible in a mousemove event handler to determine if there are any pending mousemove events in the queue? 在Javascript中,是否可以在mousemove事件处理程序中确定队列中是否有任何待处理的mousemove事件?
Or, preferably, is it possible to make the event queue skip all mousemove events in the queue except for the most recent one? 或者,最好使事件队列跳过队列中除最近事件以外的所有mousemove事件?
I'm using mousemove & other mouse events to allow users to drag elements around the screen, and I don't need to waste CPU & GPU cycles redrawing the dragged items on every mousemove event (in which I update the top & left CSS properties), as long as I can skip intermediate events quickly enough. 我正在使用mousemove和其他鼠标事件来允许用户在屏幕上拖动元素,并且我不需要浪费CPU和GPU周期在每个mousemove事件上重画拖动的项目(在此我更新了顶部和左侧的CSS属性),只要我可以足够快地跳过中间事件即可。
My site is not currently experiencing any performance or visualization problems; 我的网站目前没有任何性能或可视化问题; I just want to make my JavaScript as efficient as possible. 我只是想让我的JavaScript尽可能高效。
Use event debouncing. 使用事件反跳。 This small throttle/debounce library works well with or without jQuery. 无论是否使用jQuery, 这个小型的节流/反跳库都可以很好地工作。
Example: 例:
function someCallback() {
// snip
}
// don't fire more than 10 times per second
var debouncedCallback = Cowboy.debounce(100, someCallback);
document.getElementById('some-id').addEventListener('mousemove', debouncedCallback);
You could keep track of the last time you handled a mousemove, then skip the current one if it's too soon. 您可以跟踪上一次处理鼠标移动的时间,如果过早,则跳过当前操作。
For example: 例如:
elem.onmousemove = function() {
var lastcalled = arguments.callee.lastCallTime || 0,
now = new Date().getTime();
if( now-lastcalled < 250) return;
arguments.callee.lastCallTime = now;
// rest of code here
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.