节流函数
在规定时间内 只让函数触发
第一次生效
后面不生效
// 节流:一段时间内只执行一次某个操作,过了这段时间 如果还有操作再继续执行新的操作
const box = document.querySelector('.box')
console.log(box);
box.addEventListener('drag', throttle(() => {
console.log('test');
}))
function throttle(fn) {
let timer = null
return function () {
if (timer) return
timer = setTimeout(() => {
fn()
timer = null
}, 200)
}
}
function throttle1(fn, delay) {
// 记录上一次触发的时间
let lastTime = 0
return function () {
let nowTime = Date.now()
if (nowTime - lastTime > delay) {
// 如果现在时间-最后触发时间大于 规定触发时间delay,就调用需要被执行的函数;并且同步一下最后一次调用的时间
fn.call(this)
// 这里要call回自己否则可能出现this指向的问题
lastTime = nowTime
}
}
}
let btn = document.querySelector('.btn')
btn.addEventListener('click', throttle1(function () {
console.log(111);
}, 2000))
防抖函数
一个频繁触发的函数,在规定时间内只让
最后一次生效
,前面的不生效
function debounce(fn, delay) {
// 记录上一次定时器
let timer = null
return () => {
// 每次点击都清除上一个定时器 保证触发的是最后一次
clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this)
}, delay)
}
}
let btn = document.querySelector('.btn')
console.log(btn);
btn.onclick = debounce(() => {
console.log('debounce',);
}, 200)