防抖与节流
# 防抖函数
当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次。
const debounce = (fn, waitTime=500) => {
let timer = null;
return function() {
const self = this;
const args = [].slice.apply(arguments);
if(timer !== null) clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(self, args);
}, waitTime);
}
}
使用
let lastDateTime = new Date().getTime();
function handle() {
let nowDateTime = new Date().getTime();
console.log('鼠标移动', nowDateTime - lastDateTime);
}
window.addEventListener('mousemove', debounce(handle, 500));
# 节流函数
规定时间内,只触发一次。
const throttle = (fn, waitTime=500) => {
let isRunnig = false;
return (...args) => {
if(!isRunnig) {
isRunnig = true;
setTimeout(() => {
fn(...args);
isRunnig = false;
}, waitTime)
}
}
}
const throttle = (fn, waitTime=500) => {
let prev = Date.now();
return (...args) => {
let now = Date.now();
if (now - prev >= waitTime) {
fn(...args);
prev = Date.now();
}
}
}
// Make sure to add code blocks to your code group
使用
let lastDateTime = new Date().getTime();
function handle() {
let nowDateTime = new Date().getTime();
console.log('鼠标移动中', nowDateTime - lastDateTime);
}
window.addEventListener('mousemove', throttle(handle, 300));
上次更新: 2022/08/26, 17:06:25