1、防抖debounce:是指事件在触发n秒后执行,如果n秒内又被触发,时间重新计算。可以避免多次点击的问题(如按钮提交、scroll事件)
2、节流throttle:指一个时间内只执行一次,如果一个时间内,事件被触发多次,也只执行一次(拖拽、缩放、动画)
// 防抖使用debounce(func, wait, immediate)
const debounce = function(func, wait, immediate){
let timeId = null
function debounced(...args){
const context = this;
if (immediate) {
func.apply(context, args)
}
if (timeId) {
clearTimeout(timeId)
}
timeId = setTimeout(() => {
func.apply(context, args)
}, wait)
}
function cancel() {
if (timeId) clearTimeout(timeId);
timeId=null;
}
debounced.cancel = cancel;
return debounced
}
// 节流(时间控制)
const throttle = function(func, wait){
let previous = new Date().getTime();
function throttled(...args) {
const context = thisl
let now = new Date().getTime();
if (now - previous > wait) {
previous = now;
func.apply(context, args)
}
}
return throttled
}
// 节流(定时器)
const throttle = function(func, wait) {
let timeId = null;
function throttled(...args) {
const context = this;
if (timeId) return;
timeId = setTimeout(() => {
func.apply(context, args)
timeId = null
}, wait)
}
return throttled
}