JS防抖与节流
一. 原理及适用场景
名称 | 原理 | 适用场景 | 实现 |
---|---|---|---|
防抖 | 当事件触发n秒后执行回调,如果在n秒内又被触发,则重新计时. | 1.按钮提交场景: 防止多次提交,只提交最后一次. 2. 搜索框联想场景: 防止联想发送请求,只发送最后一次输入. | 1.非立即执行 2.立即执行 |
节流 | 规定在一个单位时间内只能触发一次函数.如果在单位时间内触发多次,只执行一次. | 1.拖拽场景: 固定时间只执行一次,防超高频次触发.2. 缩放场景: 监控浏览器resize,scroll | 1.时间戳实现 2.定时器实现 |
二. 防抖实现
非立即执行版
const debounce = (func, wait, ...args) => {
let timeout;
return function(){
const context = this;
if (timeout) clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(context, args)
},wait);
}
}
立即执行版
const debounce = (func, wait, ...args) => {
let timeout;
return function(){
const context = this;
if (timeout) cleatTimeout(timeout);
let callNow = !timeout;
timeout = setTimeout(() => {
timeout = null;
},wait)
if(callNow) func.apply(context,args)
}
}
三. 节流实现
时间戳实现
const throttle = (func, wait, ...args) => {
let pre = 0;
return function(){
const context = this;
let now = Date.now();
if (now - pre >= wait){
func.apply(context, args);
pre = Date.now();
}
}
}
定时器实现
const throttle = (func, wait, ...args) => {
let timeout;
return function(){
const context = this;
if(!timeout){
timeout = setTimeout(() => {
timeout = null;
func.apply(context,args);
},wait)
}
}
}