防抖截流:都是用来控制某个函数在一定时间内的触发次数
防抖:多次触发只执行最后一次(场景:表单校验、按钮提交、文本编辑器实时保存、搜索框输入查询、窗口大小resize)
<body>
<button id="btn">click</button>
<script>
let btn = document.getElementById('btn')
btn.onclick = debounce(btnClick)
function btnClick(event) {
console.log('防抖click----', event)
}
function debounce(fn, wait = 300) {
let timer = null
return function (...args) {
clearTimeout(timer)
timer = setTimeout(() => {
fn.call(this, ...args)
}, wait)
}
}
</script>
</body>
节流:规定时间内只触发一次(场景:鼠标点击事件、鼠标移动、监听滚动事件)
<body>
<button id="btn">click</button>
<script>
let btn = document.getElementById('btn')
btn.onclick = throttle(click)
function click(event) {
console.log('节流click', event)
}
function throttle(fn, wait = 200) {
let time = 0
return function (...args) {
let now = new Date().getTime()
if (now - time > wait) {
fn.call(this, ...args)
time = now
}
}
}
</script>
</body>