Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

防抖和节流 #71

Open
kekobin opened this issue Apr 12, 2020 · 0 comments
Open

防抖和节流 #71

kekobin opened this issue Apr 12, 2020 · 0 comments

Comments

@kekobin
Copy link
Owner

kekobin commented Apr 12, 2020

防抖 debounce

指的是强制一个函数在某个连续时间段内只执行一次,哪怕它本来会被调用多次。即在用户停止某个操作一段时间之后才执行相应的监听函数,而不是在用户操作的过程当中,浏览器触发多少次事件,就执行多少次监听函数。

常见场景:input、resize等

实现:

function debuouce(fn, delay = 300) {
	let timeout = null;
	return function (...args) {
		cleartimeout(timeout);
		
		timeout = setTimeout(() => {
			fn.apply(this, args);
		}, delay);
	}
}

节流 throttle

好比水库泄流一样,不能一下次泄太多,隔一段时间泄一次。即固定函数执行的速率,即所谓的“节流”。(“匀速”地执行)

常见场景:scroll、mousemove、touchmove

实现:

function throttle(fn, threshold = 300) {
	let timeout = null;
	let last = null; // 上次执行的时间
	return function (...args) {
		const now = Date.now();
		
		// 思路是:必须间隔threshold时间才能执行一次,否则重新定时
		if (last && now < (last + threshold)) {
			clearTimeout(timeout);
			
			timeout = setTimeout(() => {
				last = now;
				fn.apply(this, args)
			}, threshold)
		} else { // 其它情况:如第一次和最后一次,直接执行
			last = now;
			fn.apply(this, args);
		}

                // 更简洁方式
               if (now - last > delay) {
                    last = now;
			fn.apply(this, args);
               }
	}
}

image

注意:debouonce和throttle都是必包,返回的都是一个函数!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant