如何从另一个函数调用本地函数?

时间:2018-11-07 10:56:22

标签: javascript function call debouncing

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)"???*

}

2 个答案:

答案 0 :(得分:0)

也许这可以帮助:

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(() => {});
}

答案 1 :(得分:0)

让函数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>