使用防抖函数接收返回值的问题和解决方案

653 阅读2分钟

1.基础的防抖函数

  function debuonce(fun,daly=200){
    let timer;
    return function(){
        var arg = arguments;
        if(timer){
         clearTimeout(timer);
         timer = null;
         } 
        timer = setTimeout(()=>fun.apply(this,arg),daly);
      }
    }
  
  //使用防抖函数
  function a (data){
         console.log(data);
         return data;
       }
        let b = debuonce(a,300);
        b(234)    //没有执行里面的a函数 
         let c =  b(123);    // 执行b函数结果 123 
         console.log(c)   //  undefined  
     
    
    
    
```js

防抖的基本功能做到了,但是c变量并没有接收到 a函数返回的值,那么如何改造防抖函数让其有以上的功能又可以接收 a函数返回的值呢?

基于上述功能,我们可以使用promise函数去改造防抖函数

2.实现能够接收函数返回值的防抖函数

 function debuonce(fun,daly=200){
     let timer;
     return function(){
             let self = this;
             let arg = argument;
           return new Promise((resolve,reject)=>{
              if(timer){
                  clearTimeout(timer);
                  timer = null;
              }
             setTimeout(()=>{
                 try{
                 resolve(fun.apply(this,argument))
                 }catch(e){
                 reject(e);
                 }
             },daly) 
           })
         }
 }
 
 
  function a(data){
   console.log(data+1)
   return data;
 }

 var b = debounce(a,300);

    b(111).then(value=>{
      console.log(value)
    })

   b(111).then(value=>{
      console.log(value)    //接收到a函数返回的值
    })
    
 //控制台输出  112   111  
 

```js

上述代码执行结果成功的实现了防抖 并且使用promise函数改造之后 能够接收到原本函数执行之后返回的数据。

3.拓展

在实现此方法之前通过网上搜索查找过一些资料,虽然没有找到想要的答案但是其中发现了一个关于防抖函数的细节问题,在此留下记录

当监听事件里面使用防抖函数,且防抖函数中需要传值问题

<button id ='btn'> </button>
```js 
//a参数 代表上面的函数
//使用平常方法后面加上() 传值 里面的防抖函数会立刻执行 
 document.getElementById("btn").addEventListener('click',debuonce(a)('传递的参数'));
 
 //可以使用bind函数来实现我
 document.getElementById("btn").addEventListener('click',debuonce(a).bind('传递的参数'));