const debounceDom = document.getElementById('debounce')
// 使用防抖函数,确保在连续触发 keyup 事件时只触发一次 ajax 函数
debounceDom.addEventListener('keyup', debounce(ajax, 500))
// 模拟一个 ajax 请求
function ajax() {
console.log('这是一个请求');
}
// 实现防抖的函数
function debounce(fn, time) {
let timer = null
return function () {
if (timer) { //说明上次定时器还没有执行完 清除上次定时器
clearTimeout(timer)
}
timer = setTimeout (() => {
// 箭头函数没有this、arguments,所以apply使用不用提前存,用的就是外部的
fn.apply(this, arguments)
}, time)
}
}
每隔一段时间,只执行一次函数
侧重点在于隔段时间一次,隔段时间一次
function throttle (fn, delay) {
let prevTime = Date.now();
return function(){
if(Date.now() - prevTime > delay){
fn.apply(this, arguments)
prevTime = Date.now()
}
}
}
function throttle (fn, delay) {
let timer = null
return function() {
if(timer) return
timer = setTimeout (() => {
fn,apply(this, arguments)
timer = null
}, delay)
}
}