手撕源码(节流)

142 阅读1分钟

1.定义:节流就是从高频变成低频
2.思路:我自己跟着老师学到了 一种方法;又在牛客上阅读并学会了“bbin”博主的第二种方法。
方法一:1.使用setTimeout函数+timer的判断:timer为定时器,如果已有定时器在运行;那就不再注册新的定时器了。
2.再使用remaining,去判断当前剩余时间;注册定时器。

方法一:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<button type="button" id="btn">快速点击</button>
	</body>
</html>
<script type="text/javascript">
	function func() {
		console.log('ok')
	}

	function throttle(func,wait = 500) {
		let timer = null,
			previous = 0;
		return function anonymous(...params) {
			let now = new Date(),
				remaining = wait - (now - previous);
			if (remaining <= 0) {
				clearTimeout(timer);
				console.log('1')
				timer = null;
				previous = now;
				func.call(this, ...params)
			} else if (!timer) {
				timer = setTimeout(() => {
					clearTimeout(timer);
					timer = null;
					previous = new Date();
					func.call(this, ...params)
				}, remaining)
			}
		}
	}
	btn.onclick = throttle(func, 5000);

方法二:

	function throttle(func,delay) {
		let timer = null;
		return function anonymous(...params) {
			if (!timer) {
				timer = setTimeout(() => {
					timer = null;
					clearTimeout(timer);
					func.apply(this, ...params)
				}, delay)
			}
		}
	}

相信两者对比的话,就能明白思路了。
方法一较为复杂,但是是点击立即触发,然后每隔一定时间间隔,触发一次。
方法二思路很好,但是是点击之后,过了时间间隔之后再进行触发。
所以两者结合,就可以设计出既可以立即触发;也可以时间间隔的最后一次触发。