函数防抖(debounce):触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间。
函数节流(throttle):高频事件触发,但在n秒内只会执行一次,所以节流会稀释函数的执行频率。
函数节流(throttle)与 函数防抖(debounce)都是为了限制函数的执行频次,以优化函数触发频率过高导致的响应速度跟不上触发频率,出现延迟,假死或卡顿的现象。
如何封装防抖函数
function debounce(fn,delay){
var timeout = null;
return function(){
if(timeout){
clearTimeout(timeout);
}
timeout = setTimeout(fn,delay)
}
}
function handle(){
console.log(Math.random())
}
window.addEventListener('mousemove',debounce(handle,1000))
如何封装节流函数
方法一 通过date设定
function throttle(fn,delay){
let timer,start=0;
return function(){
let now = new Date().getTime();
if(now > start + delay){
fn();
start = now;
}
}
}
function handle(){
console.log(Math.random());
}
window.addEventListener("mousemove",throttle(handle,1000));
方法二 定时器方案
function throttle(fn,delay){
let timer = null;
return function(){
if(!timer){
timer = setTimeout(function(){
fn();
timer = null;
},delay)
}
}
}
function handle(){
console.log(Math.random());
}
window.addEventListener("mousemove",throttle(handle,1000));
节流函数的使用场景
- 懒加载、滚动加载、加载更多或监听滚动条位置;
- 百度搜索框,搜索联想功能;
- 防止高频点击提交,防止表单重复提交;