Open dashengzi66 opened 3 years ago
定义: 指连续触发事件但是在 n 秒中只执行一次函数
<div id="content" style="height:150px;line-height:150px;text-align:center; color: #fff;background-color:#ccc;
font-size:80px;"></div>
方案1--时间戳
function throttle(func, wait) {
let previous = 0;
return function() {
let now = Date.now();
let context = this;
let args = arguments;
if (now - previous > wait) {
func.apply(context, args);
previous = now;
}
}
}
content.onmousemove = throttle(count,1000);
方案2--定时器
function throttle(func, wait) {
let timeout;
return function() {
let context = this;
let args = arguments;
if (!timeout) {
timeout = setTimeout(() => {
timeout = null;
func.apply(context, args)
}, wait)
}
}
}
content.onmousemove = throttle(count,1000);
防抖
定义: 是指触发事件后在n秒内函数只能执行1次, 如果在n秒内又触发了事件, 则会重新计算函数执行时间
方案1--包含立即执行