js手写节流和防抖

节流:连续触发事件但在n秒中只执行一次函数。

function throttle(func, delay) {
	let pre = 0;
	return function() {
		let context = this;
		let args = arguments;
		let now = new Date();
		if (now - pre > delay) {
			func(context, args);
			pre = now;
		} 
	}
}
function throttle(func, delay) {
	let timer = null;
	return function() {
		let context = this;
		let args = arguments;
		if (timer) {
			return;
		}
		timer = setTimeout(function() {
			func(context, args);
			timer = null;
		}, delay)
	}
}

防抖:触发事件后在n秒内函数只执行一次,如果n秒内又触发了事件,则会重新计算函数执行事件。

function debounce(func, delay) {
	let timer = null;
	return function() {
		let context = this;
		let args = arguments;
		clearTimeout(timer);
		timer = setTimeout(function() {
			func(context, args);
		}, delay)
	}
}

版权声明:本文为bidepanm原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。