js 防抖节流

 1 // 防抖
 2 function debounce(func,delay){
 3     let timer = null
 4     return function(){
 5         let context = this
 6         let args = arguments
 7         if(timer) clearTimeout(timer)
 8         timer = setTimeout(()=>{
 9             func.apply(context,args)
10         },delay)
11     }
12 }
13 // 通过setTimeout实现 节流
14 function throttle(func,delay){
15     let timer = null
16     return function(){
17         if(!timer){
18             let context = this
19             let args = arguments
20             timer = setTimeout(()=>{
21                 timer = null
22                 func.apply(context,args)
23             },delay||1500)
24         }
25     }
26 }
27 // 通过时间比较实现 节流
28 function throttle(func,gapTime){
29     if(gapTime == null || gapTime == undefined){
30         gapTime = 1500
31     }
32     let _lastTime = null
33     return function(){
34         let _nowTime = + new Date()
35         if(_nowTime - _lastTime > gapTime || !_lastTime){
36             func()
37             _lastTime = _nowTime
38         }
39     }
40 }
作者:胡倩倩0903
本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/kitty-blog/p/14598492.html