JS防抖和节流函数

77 阅读1分钟

防抖函数

回调函数会在停止触发的规定时间后执行

function debounce(fn,delay){
    let timer = null
    return function() {
        if(timer){
            clearTimeout(timer) 
        }
        timer = setTimeout(fn,delay)
    }
}

节流函数

回调函数会每隔规定时间执行一次

function throttle(fn, delay) {
	let date = new Date();
	return function() {
		const currentDate = new Date();
		if (currentDate - date > delay) {
			fn();
			date = currentDate;
		}
	}
}