防抖和节流

91 阅读1分钟

防抖

函数防抖的关键在于,在一个动作发生一定时间之后,才执行特定事件

    let num = 1;
	let box = document.querySelector('.box');
	let changeNum = function () {
		box.innerHTML = num++;
	};

    let deBounce = function(fn, delay) {
		let timer = null; // 防止setTimeOut累加
		return function (...args) {
    		if(timer) {
    		   clearTimeout(timer);
    		}
		 timer = setTimeout(() => {
			fn(...args)
			}, delay)
		}
	}

	box.onmousemove = deBounce(changeNum, 1000);

节流

当持续触发事件时,保证一定时间段内只调用一次事件处理函数

	let num = 1;
	let box = document.querySelector('.box');
	let changeNum = function () {
		box.innerHTML = num++;
	};

	let throttle = function(fn, delay) {
		let flag = true;
		return function(...args) {
			if(!flag) return;
			flag = false;
			setTimeout(() => {
				fn(...args)
				flag = true;
			}, delay)
			
		}
	
	}
	box.onmouseover = throttle(changeNum, 1000)