函数节流(throttle)和防抖(debounce)

一、节流和防抖

我们知道过于频繁的dom操作会导致页面卡顿甚至浏览器崩溃,节流和防抖可以用于缓解在某段时间内频繁调用函数带来的压力。

节流:在某段时间内,只允许函数执行一次,随后进入下一个执行周期

防抖:在连续的操作之后过一段时间才会执行一次函数

二、函数实现

1、防抖debounce

 1 function debounce(fun, delay){
 2   let timer;
 3   return function(){
 4     let context = this;
 5     let args = arguments;
 6     clearTimeout(timer);
 7     timer = setTimeout (()=>{
 8         fun.apply(context,args);      
 9 },delay)
10 }    
11 }

2、节流throttle

 1 function throttle(fun, delay, mustRunDelay){
 2    let timer = null
 3    let start
 4    return function(){
 5      let context = this
 6      let args = arguments
 7      let now = new Date().getTime()
 8      clearTimeout(timer)
 9      if(!start){
10        start = now;
11      }    
12      if(now - start >= mustRunDelay){
13         fun.apply(context, args)  
14      }else{
15         timer = setTimeout(()=>{
16             fun.apply(context, args)
17         },delay)
18      }
19    }              
20 }

三、应用场景

防抖:

  • 对用户输入的验证,不在输入过程中就处理,停止输入后进行验证足以;
  • 提交ajax时,不希望1s中内大量的请求被重复发送。

节流:

  • 对用户输入的验证,不想停止输入再进行验证,而是每n秒进行验证;
  • 对于鼠标滚动、window.resize进行节流控制。
原文地址:https://www.cnblogs.com/sue7/p/9792805.html