我有这样的代码:
$("body").mousemove(function (event) {
var lowestspanelm = findNearestSpan(gg_phone_spans, event);
});在鼠标移动期间,这会产生太多的事件并增加CPU负载,大约需要1分钟左右才能恢复正常。
为了减少这个负载,我想要的是只在鼠标停止至少1/2秒时才采取行动。
怎么做呢?
发布于 2021-05-07 12:28:07
如注释所示,这通常称为debounce函数,并可在许多通用库中使用。自己编写(一个简单的版本)也相当容易。
$(document).on("mousemove",debounce(function(event) {
console.log("This will only happen after you stop moving the mouse for 1/2 second")
},500));
function debounce(fn, time){
let timer = null;
return (evt) => {
clearTimeout(timer);
timer = setTimeout( () => fn(evt), time);
};
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
发布于 2021-05-07 13:02:33
虽然你的问题指向一个方向,你需要一个退出函数,我的建议是,你尝试一个节流函数代替。
被取消的函数只有在不再有传入事件时才会触发--节流函数只会偶尔触发
$("body").mousemove(throttle(function (event) {
var lowestspanelm = findNearestSpan(gg_phone_spans,event);
}, 500));只要有传入事件,这只会触发每一次.5秒。
这样你就不需要jQuery了。
document.addEventListener('mousemove', throttle(function (event) {
var lowestspanelm = findNearestSpan(gg_phone_spans,event);
}, 500));以下是对这些差异的说明。如果你悬停在普通元素上,背景颜色会随着每个像素的移动而改变。
如果你在节流阀元素内移动,只要你移动,颜色每半秒就会改变一次。
如果在DEBOUNCE元素中移动,则在停止移动(或从元素中移出)之后,颜色只会更改.5秒。
这里是互相击退和节流的地方
function debounce(callback, wait) {
var timeout;
return function(e) {
clearTimeout(timeout);
timeout = setTimeout(() => {
callback(e);
}, wait);
}
}
function throttle(callback, wait) {
var timeout
return function(e) {
if (timeout) return;
timeout = setTimeout(() => (callback(e), timeout=undefined), wait)
}
}
function onMove(e) {
e.target.classList.toggle('gold')
}
document.querySelector('.normal').addEventListener('mousemove', onMove)
document.querySelector('.throttle').addEventListener('mousemove', throttle(onMove, 500))
document.querySelector('.debounce').addEventListener('mousemove', debounce(onMove, 500)).normal,
.throttle,
.debounce {
width: 100px;
height: 100px;
margin: 25px;
background: silver;
border: 1px solid gold;
}
.normal.gold,
.throttle.gold,
.debounce.gold {
background: gold;
}
body {
display: flex;
}<div class="normal">NORMAL</div>
<div class="throttle">THROTTLE</div>
<div class="debounce">DEBOUNCE</div>
发布于 2021-05-07 12:24:59
一种可能的方法是使用超时:
var mouseTimeout;
$("body").mousemove(function (event) {
clearTimeout(mouseTimeout);
mouseTimeout = setTimeout(function() {
var lowestspanelm = findNearestSpan(gg_phone_spans,event);
}, 500);
});您可以调整500,使其触发或多或少的频率。
https://stackoverflow.com/questions/67434871
复制相似问题