防抖:在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时。

debounce: function(fun, delay) {
	return function(args) {
		let that = this;
		let _args = args;
		clearTimeout(fun.id);
		fun.id = setTimeout(() => {
			fun.call(that, _args)
		}, delay)
	}
}

节流:规定在一个单位时间内,只能触发一次函数。如果这个单位时间内触发多次函数,只有一次生效。

throttle: function(fn, delay) {
	let timer = true;
	return function(args) {
		let that = this;
		let _args = arguments;
		if(!timer){
		   return false;
		}
		timer = false;
		setTimeout(() => {
			fn.apply(that, _args)
			timer = true;
		}, delay)
	}
}

使用

click: debounce(function() {
    
    console.log('业务代码')

}, 3000)


click: throttle(function() {
    
    console.log('业务代码')

}, 3000)