事件防抖

24 阅读1分钟

export function debounce(func, wait = 300, immediate) {
	let timeout, result;

	const later = function (context, args, timestamp) {
		const last = +new Date() - timestamp;

		if (last < wait && last > 0) {
			timeout = setTimeout(() => later(context, args, timestamp), wait - last);
		} else {
			timeout = null;
			if (!immediate) {
				result = func.apply(context, args);
				if (!timeout) context = args = null;
			}
		}
	};

	return function (...args) {
		let context = this;
		const timestamp = +new Date();
		const callNow = immediate && !timeout;

		if (!timeout) timeout = setTimeout(() => later(context, args, timestamp), wait);

		if (callNow) {
			result = func.apply(context, args);
			context = args = null;
		}

		return result;
	};
}