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

手写防抖和节流 #16

Open
GGXXMM opened this issue Aug 9, 2019 · 0 comments
Open

手写防抖和节流 #16

GGXXMM opened this issue Aug 9, 2019 · 0 comments
Labels
⭐️ js js knowledge

Comments

@GGXXMM
Copy link
Owner

GGXXMM commented Aug 9, 2019

防抖概念

防抖(Debounce)是指,动作发生n秒后触发事件,如果n秒内再次触发了,重新计时。
经典例子:限制鼠标连击触发
image

实现防抖

function debounce(fn, wait=50) {
	let timer = null;
	// 将debounce处理结果当作函数返回
	return function() {
		if(timer) clearTimeout(timer);
		// 设定一个新的定时器,定时器结束后执行该函数
		timer = setTimeout(() =>{
			fn.apply(this, arguments)
		}, wait)
	}
}

function realFunc(){
    console.log("防抖成功");
}

var btn = document.getElementById('debounceBtn');
btn.addEventListener('click', debounce(realFunc, 1000));// 鼠标点击限制1s后执行

节流概念

节流(Throttle)则是指定时间间隔内,只执行一次任务。在这段时间内,如果又发生了动作,无视该动作。
image

实现节流

实现节流主要有2种方案:

  • 使用时间戳
function throttle(fn, wait=50) {
	// 上次执行fn时间
	let previous = 0
	// 将throttle处理结果当作函数返回
	return function() {
		// 获取当前时间
		let now = +new Date();
		if(now - previous > wait) {
			previous = now;
			fn.apply(this, arguments);
		}
	}
}

function realFunc(){
    console.log("节流成功");
}

var btn = document.getElementById('throttleBtn');
btn.addEventListener('click', throttle(realFunc, 500));
  • 设置定时器
function throttle(fn, wait=50) {
	let timeout = null;
	return function() {
		if(!timeout) {
			timeout = setTimeout(()=>{
				fn.apply(this, arguments)
				timeout = null;
			}, wait);
		}
	}
}
@GGXXMM GGXXMM added the ⭐️ js js knowledge label Dec 7, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
⭐️ js js knowledge
Projects
None yet
Development

No branches or pull requests

1 participant