节流防抖

151 阅读1分钟
防抖:
	在一个动作执行后立即充值状态 单位时间内不再触发的话 函数执行 如果单位时间内触发 则重新计时
	//增加立即执行版本
	function debounce(func, wait, immediate){
		let timer = null;
		
		return function(...args){
			let context = this;
			//立即执行版本
			if (immediate){
				let callNow;
				if (timer){
					clearTimeout(timer)
				}
				callNow = !timer;
				timer = setTimeout(() => {
					timer = null;
				}, wait)
				if (callNow) func.apply(context, args);
			}else{
				if (!timer) {
					clearTimeout(timer);
				}
				//这样的执行方式不会立即触发一次func 
				timer = setTimeout(() => {
					//func的执行环境为debounce作用域 debounce的作用域继承函数被调用处的作用域 因此func的作用域还是指向被调用处的作用域
					func.apply(context, args);
					timer = null;
				}, wait)
			}
			
		}
	}
	
	
节流:  在高速的触发过程中  在单位时间内的触发 会被屏蔽执行 直到单位时间过去  降低调用频率
	
	//@params func<Function> wait<Number> type<String>
	function throttle(func, wait, type){
		let timer = null;
		//缓存变量记录时间戳
		let previous = 0;
		
		return function(...args){
			//继承被调用处的作用域
			let context = this;
			
			if (type == "timeStamp"){
				let nowTime = new Date().getTime();
				if (nowTime - previous >  wait){
					func.apply(context, args);
					previous = nowTime;
				}
			}else{
				//这样的方法 是记录性的 只要初始触发一次 则肯定会触发一次初始调用 可以通过时间戳的形式去掉初始调用
				if (!timer){
					timer = setTimeout(() => {
						func.apply(context, args);
						timer = null;
					}, wait)
				}
			}
		}
	}