节流
概念:规定一个单位时间,这个单位时间内只能有一次触发事件的回调函数执行,如果该时间内事件出发多次,只有一次生效 适用场景:
- dom元素拖拽
- 刷新率
- canvas画笔
// 节流(一段时间执行一次之后,就不执行第二次)
function throttle(fn, delay){
let canUse = true
return function(){
if(canUse){
fn.apply(this, arguments)
canUse = false
setTimeout(()=>canUse = true, delay)
}
}
}
const throttled = throttle(()=>console.log('hi'))
throttled()
throttled()
防抖
概念:规定一个时间,事件触发后在n秒后执行回调,如果n秒内又被触发,则重新计时 适用场景:
- 防止表单多次提交
- 输入框连续输入进行ajax验证时,减少请求次数
- 判断scroll是否滑到底部
// 防抖(一段时间会等,然后带着一起做了)
function debounce(fn, delay){
let timerId = null
return function(){
const context = this
if(timerId){window.clearTimeout(timerId)}
timerId = setTimeout(()=>{
fn.apply(context, arguments)
timerId = null
},delay)
}
}
const debounced = debounce(()=>console.log('hi'))
debounced()
debounced()