函数防抖debounce与节流throttle

//防抖
function debounce(fn,delay){
    let timer = null
    return (...args)=>{
        if(timer) clearTimeout(timer)
        timer = setTimeout(()=>{
            fn.apply(this,args)
        },delay)
    }
}

// 节流throttle
function throttle(fn,delay){
    let late = +new Date()
    return function(...args){
        let now = +new Date()
        if(now - late > delay){
            late = now
            fn.apply(this,args)
        }
    }
}
复制代码

示例:


"en">

    "UTF-8">
    "viewport" content="width=device-width, initial-scale=1.0">
    "X-UA-Compatible" content="ie=edge">
    Document


    输入框1:type="text" id="input1" />
输入框2:type="text" id="input2" /> 复制代码

你可能感兴趣的:(函数防抖debounce与节流throttle)