防抖:防止老年帕金森,对于频繁触发某个操作,我们只识别一次(只触发一次)
- @params
- func[function]:最后要触发执行的函数
- wait[number]:设定频繁的界限
- immediate[boolean]:默认多次操作,识别最后一次,如果值为true,识别第一次
- @return
- 可以被调用执行的函数
function debounce(func,wait=300,immediate = false) {
let timer = null;
return function annoymous(...params) {
let now = immediate && !timer;
clearTimeout(timer);
timer = setTimeout(()=>{
timer = null;
!immediate ? func.call(this,...params):null;
},wait);
now ? func.call(this,...params) :null
}
}
节流:在一段频繁操作中,可以触发多次,但是触发的频率是由自己指定的
- @params
- func[function]:最后要触发执行的函数
- wait[number]:触发的频率
- @return
- 可以被调用执行的函数
function throttle(func,wait=300){
let timer = null,
previous = 0
return function annoymous(){
let now = new Date(),
remaining=wait - (now - previous)
if(remaining<=0){
timer = null
//两次操作的间隔已经超过wait了
window.clearTimeout(timer)
previous = now
func.call(this,...parems)
} else if(!timer) {
//两次操作时间的间隔不符合触发频率
timer = setTimeout(()=>{
timer = null
previous = new Date()
func.call(this,...params)
},remaining)
}
}
}
function handle(){
console.log('ok)
}
window.onscroll = handle
window.onscroll = throttle(handle)
window.onscroll = function annoymous()