先说定义: 防抖:连续触发的事件,如果不加节制,就会不断响应事件,所以需要让设定一个时间间隔x,在x时间间隔内触发则事件不响应,超过x时间才响应一次。
// 利用闭包封装作用域
function debounce(func, delay) {
let timeout
return function() {
clearTimeout(timeout)
timeout = setTimeout(() => {
func()
}, delay)
}
}
function print(str) {
return function() {
console.log(str)
}
}
// 使用, 不断点击,只有停止点击2s后才会触发一次。
btn.onclick = debounce(print('hello'), 2000)
更完善的做法,目标函数可带多个参数
const print = (param1, param2) => {
console.log(param1 + '--' + param2)
}
const debounce = (func, wait = 500) => {
let timer = null
return function() {
const context = this
const args = arguments
console.log(args)
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
func.apply(context, args)
}, wait)
}
}
const test = debounce(print, 1000)
test('aa', 'bb')
test('aa', 'bb')
test('aa', 'bb')
节流:上面防抖虽然可以让点击事件在等待一定时间后才能触发,但是不能在点击期间每隔一段时间就触发一次,所以有了节流,让不断点击的过程中每隔x时间就触发一次。
function throttle(func, delay) {
let flag = true
return function() {
if (!flag) {
return
}
flag = false
setTimeout(() => {
func()
flag = true
}, delay)
}
}
function print(str) {
return function() {
console.log(str)
}
}
// 使用, 不断点击,每隔2s就会触发一次。
btn.onclick = throttle(print('hello'), 2000)