【问题标题】:How to call a local function from another function?如何从另一个函数调用本地函数?
【发布时间】:2019-04-10 19:15:38
【问题描述】:
function A {

      *// Inside function A We have below lines of code to do debouncing*

const debounce = (func, delay) => { 
    let debounceTimer 
    return function() { 
        const context = this
        const args = arguments 
            clearTimeout(debounceTimer) 
                debounceTimer 
            = setTimeout(() => func.apply(context, args), delay) 
    } 
}  
button.addEventListener('click', debounce(function() { 


      *// Some Code Will be Ecexuted here after 3000 ms*


                        }, 3000)); 

      *// function A ends here*
}

现在我想调用“clearTimeout(debounceTimer)”或任何其他可能的代码来清除另一个函数(函数 B)中去抖动的时间

function B {

        *// How To Call "clearTimeout(debounceTimer)"???*

}

【问题讨论】:

  • *//an Unknown Syntax to do "clearTimeout(debounceTimer)"* 应该是您要找的吗?
  • 是的...我想知道如何在这里调用 clearTimeout(debounceTimer)...
  • 您的代码有点混乱,语义上函数A和B需要后跟括号...但是不清楚您要完成什么。让我明白如果我点击按钮会发生什么?
  • RxJS 非常擅长处理资源,无论调用/定义上下文如何
  • 你为什么要使用const context = thisconst 值是块范围的

标签: javascript function call debouncing


【解决方案1】:

让函数 A 返回一个对象,该对象为您提供清除超时的句柄。

比如这样:

const button = document.getElementById("btn");
const cancel = document.getElementById("can");
const log = document.getElementById("log");

function A() {
    const state = {
        clear: () => null
    }
    
    const debounce = (func, delay) =>
        (...args) => { 
            state.clear();
            state.clear = clearTimeout.bind(null, 
                    setTimeout(func.bind(null, ...args), delay));
        };
    
    button.addEventListener('click', debounce(function() { 
        log.textContent = "Message arrived at " + Date().match(/\d+:\d+:\d+/) 
                          + "\n" + log.textContent;
    }, 3000)); 

    return state;
}

function B(state) {
    state.clear();
}

const state = A();
cancel.addEventListener('click', B.bind(null, state));
<button id="btn">Send Message</button>
<button id="can">Abort Message</button>
<pre id="log"></pre>

【讨论】:

    【解决方案2】:

    也许这会有所帮助:

    function A(func) {
       const obs$ = Observable.fromEvent(button, 'click')
                       .pipe(delay(debounceTime), map(args => func(args)));
       return obs$;
    }
    
    // Now you are free to use observable in function B.
    function B() {
       const obs$ = A(/*your function*/);
       obs$.subscribe(res => /*use result*/)
           // Doing this will clear everything.
           .unsubscribe(() => {});
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-06
      • 2015-07-03
      • 2012-05-14
      • 2021-07-03
      • 2020-11-17
      • 1970-01-01
      • 2014-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多