實(shí)現(xiàn)節(jié)流去抖函數(shù)
標(biāo)簽:
JavaScript
完整高频题库仓库地址:https://github.com/hzfe/awesome-interview
完整高频题库阅读地址:https://febook.hzfe.org/
节流
1. 基本概念
throttle(func, wait)
每 wait 毫秒内最多只调用一次 func。
2. 应用场景
-
搜索框输入时的实时联想。
-
监听 scroll 事件计算位置信息。
3. 流程图
4. 编写代码
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);
}
};
}
去抖
1. 基本概念
debounce(func, wait)
自最近一次触发后延迟 wait 毫秒调用 func。
2. 应用场景
-
注册时输入完用户名后检测是否被占用。
-
监听 resize 事件计算尺寸信息。
3. 流程图
4. 编写代码
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);
};
}
點(diǎn)擊查看更多內(nèi)容
1人點(diǎn)贊
評(píng)論
評(píng)論
共同學(xué)習(xí),寫下你的評(píng)論
評(píng)論加載中...
作者其他優(yōu)質(zhì)文章
正在加載中
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會(huì)直接到老師賬戶
支付方式
打開微信掃一掃,即可進(jìn)行掃碼打賞哦