手写代码

43 阅读1分钟

防抖函数的实现

防抖函数是指事件被触发n后在触发,如果n秒内事件在触发,则重新计时

function debounce (fn,delay=500){
    let timer =null 
    return function (){
        let _this = this,
            args = [...arguments].slice(1)
        if(timer){
            clearTimeout(timer)
            timer = null
        }
        timer = setTimeout(()=>{
            fn.apply(_this,args)
        },delay)
            
     }
 }   

节流函数的实现

节流函数是指规定一个单位时间,在这个单位时间内,只能有一次触发事件的函数执行,如果在单位时间内某个事件函数被多次执行,只有一次被生效

function throttle(fn,delay=500){
    let curTime = Date.now()
    return function(){
        let _this = this,
            args = [...arguments].slice(1) 
            nowDate = Date.now()
        if(nowDate - curTime >= delay){
            curTime = Date.now()
            return fn.apply(_this,)
        }
    }
}