首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从另一个函数调用本地函数?

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

Stack Overflow用户
提问于 2018-11-07 18:56:22
回答 2查看 161关注 0票数 0
代码语言:javascript
复制
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)中的去抖动超时。

代码语言:javascript
复制
function B {

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

}
EN

回答 2

Stack Overflow用户

发布于 2018-11-07 20:02:29

也许这可能会有所帮助:

代码语言:javascript
复制
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(() => {});
}
票数 0
EN

Stack Overflow用户

发布于 2018-11-07 20:12:30

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

例如,像这样:

代码语言:javascript
复制
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));
代码语言:javascript
复制
<button id="btn">Send Message</button>
<button id="can">Abort Message</button>
<pre id="log"></pre>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53188104

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档