防抖和节流是前端岗位面试的必问内容,听起来很高大上,我们来轻松地记住其概念和用法。
防抖
概念:防抖是指在事件触发后,只有在指定的时间段内没有再次触发,函数才会执行。如果在这个时间段内再次触发事件,则重新计时。
看概念非常晦涩难懂,我们把它放到游戏场景中。大家玩过moba游戏的都知道回城,回城不能被打断,如果打断了需要重新开始进度条等待回城。
应用:输入框搜索、表单验证
function throttle(func, limit) {
let inThrottle;
return function() {
const args = arguments;
const context = this;
if (!inThrottle) {
func.apply(context, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
}
}
节流
概念:节流是指在一定时间内,无论事件被触发多少次,只允许函数执行一次。
节流可以类比为游戏的技能冷却,我再怎么点,一段时间内也只能放一次技能。
应用:滚动事件、按钮点击
function debounce(func, delay) {
let timeoutId;
return function() {
const args = arguments;
const context = this;
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(context, args), delay);
}
}
希望能帮到你!