const button = document.getElementById('btn_1')
function payMoney() {
console.log('支付成功')
}
function debounce(func, delay) {
// 先定义,才可以清除,定义到外围是因为所以独立执行的函数都能通过闭包的形式对timer这个变量进行操作
let timer = null
// 使用高阶函数的原因防止定义时就执行
return function() {
// 如果不保存this,那么因为回调的原因运行时已经在window下了
let context = this
let args = arguments
if (timer) {
// 正在计时中,并且再次触发相同事件,所以要取消计时并且重新开始计时
clearTimeout(timer)
}
timer = setTimeout(function () {
func.apply(context, args)
}, delay)
}
}
button.addEventListener('click', debounce(payMoney, 1000))
function coloring() {
let r = Math.floor(Math.random() * 255)
let g = Math.floor(Math.random() * 255)
let b = Math.floor(Math.random() * 255)
document.body.style.background = `rgb(${r}, ${g}, ${b})`
}
function throttle(func, delay) {
let timer
return function() {
let context = this
let args = arguments
if (timer) {
// 如果timer被赋值了,那就不执行任务直接返回
return
}
// 如果timer没有被赋值或者任务已经执行完了,就位timer赋值进行延迟执行
timer = setTimeout(function() {
func.apply(context, args)
// 不使用clearTimeout(),是因为这个清空行为是在延迟执行任务以后发生的
timer = null
}, delay)
}
}
window.addEventListener('resize', throttle(coloring, 2000))
防抖简版:
function debounce(func, delay) {
let timer
return (...args) => {
if (timer) {
// 正在计时中,并且再次触发相同事件,所以要取消计时并且重新开始计时
clearTimeout(timer)
}
timer = setTimeout(() => {
func.apply(this, args)
}, delay)
}
}
节流简版:
function throttle(func, delay) {
let timer
return (...args) => {
if (timer) {
// 如果timer被赋值了,那就不执行任务直接返回
return
}
// 如果timer没有被赋值或者任务已经执行完了,就为timer赋值进行延迟执行
timer = setTimeout(() => {
func.apply(this, args)
// 不使用clearTimeout(),是因为这个清空行为是在延迟执行任务以后发生的
timer = null
}, delay)
}
}