节流和防抖

73 阅读1分钟

防抖:保证只响应最后一次

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

节流:n秒内只触发一次

function throttle(fn,delay){
	let timer = null
    	return function(){
    	let context = this
        let args = arguments
        if(!timer) setTimeout(function(){
            fn.apply(context,args)
            timer = null
        },delay)
    }
}