-
Notifications
You must be signed in to change notification settings - Fork 1
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
【JavaScript】防抖和节流 #8
Labels
Comments
防抖和节流先初步了解到这边吧,还有两篇文章没看完,之后再补一下
以及,需要自己不看任何资料的前提下手动实现出来。 |
节流和节流比较简单清楚的实现节流function throttle(func, wait) {
let lastTime = 0;
let timer = null;
return function () {
if (timer) {
clearTimeout(timer);
timer = null;
}
let self = this;
let args = arguments;
let nowTime = +new Date();
const remainWaitTime = wait - (nowTime - lastTime);
if (remainWaitTime <= 0) {
lastTime = nowTime;
func.apply(self, args);
} else {
timer = setTimeout(function () {
lastTime = +new Date();
func.apply(self, args);
timer = null;
}, remainWaitTime);
}
};
} 防抖function debounce(func, wait) {
let timer = null;
return function () {
if (timer) {
clearTimeout(timer);
timer = null;
}
let self = this;
let args = arguments;
timer = setTimeout(function () {
func.apply(self, args);
timer = null;
}, wait);
};
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
概念
函数节流(throttle)与 函数防抖(debounce)都是为了限制函数的执行频次,以优化函数触发频率过高导致的响应速度跟不上触发频率,出现延迟,假死或卡顿的现象。
两者的区别是:防抖是虽然事件持续触发,但只有等事件停止触发后 n 秒才执行函数,节流是持续触发的时候,每 n 秒执行一次函数。
防抖(debounce)
防止抖动,以免把一次事件误认为多次。防抖重在清零
clearTimeout(timer)
。简单实现:
防抖函数
实现:
timer
是null
,调用later()
,若immediate
为true
,那么立即调用func.apply(this, params)
;如果immediate
为false
,那么过wait
之后,调用func.apply(this, params)
timer
已经重置为null
(即setTimeout
的倒计时结束),那么流程与第一次触发时一样,若timer
不为null
(即 setTimeout 的倒计时未结束),那么清空定时器,重新开始计时。防抖的应用场景
节流(throttle)
控制事件发生的频率。节流重在开关锁
timer = null
。简单实现:
节流函数
节流的应用场景
参考资料
The text was updated successfully, but these errors were encountered: