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

1、节流和防抖ajax

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

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

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

2、函数实现函数

一、防抖debouncethis

 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 }

二、节流throttlespa

 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 }

3、应用场景code

防抖:blog

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

节流:get

  • 对用户输入的验证,不想中止输入再进行验证,而是每n秒进行验证;
  • 对于鼠标滚动、window.resize进行节流控制。
相关文章
相关标签/搜索