【问题标题】:Why is the timeout variable shareable in this case?为什么在这种情况下超时变量是可共享的?
【发布时间】:2016-12-08 13:50:33
【问题描述】:

answers to this question 中有人明智地指出了这一点

timeout 变量在每次调用 即使在 debounce 本身返回之后,也可以生成函数,并且可以 切换不同的呼叫。

这对我来说不太有意义。由于 timeout 变量对于每次 debounce 调用都是本地的,它不应该是可共享的,不是吗?

附言虽然是闭包,但每次调用都应该有不同的闭包,它们只是在母函数返回后同时延长寿命,但它们不应该互相交谈,对吧?

这是另一个问题的功能:

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds.
function debounce(func, wait, immediate) {
    var timeout;              //Why is this set to nothing?
    return function() {
        var context = this, 
        args = arguments;
        clearTimeout(timeout);   // If timeout was just set to nothing, what can be cleared? 
        timeout = setTimeout(function() {
             timeout = null;
             if (!immediate) func.apply(context, args);
        }, wait);
        if (immediate && !timeout) func.apply(context, args);  //This applies the original function to the context and to these arguments?
     }; 
};

【问题讨论】:

    标签: javascript scope closures settimeout debouncing


    【解决方案1】:

    是的,每次调用debounce 都会得到一组全新的内容,但您不会重复调用debounce。您正在调用一次debounce,然后重复调用从debounce 返回的函数。该函数在timeout 结束。

    var f = debounce(func, wait, immediate);
    f();  // won't call func immediately
    f();  // still won't call func 
    // wait a while, now func will be called
    

    您只需多次调用debounce 本身来设置多个去抖函数(在上面的示例中为gh)。

    【讨论】:

    • “上下文”变量有实际用途吗?在我的调试测试中,“上下文”变量总是指的是 Window 对象。我想这是因为它是一个匿名函数。会不会有其他用途?谢谢。
    • 我想您可以将返回的闭包分配给一个对象,并且该对象将在原始func 中变为thisvar x = { f : debounce(func,w,i) }; x.f(); }
    • 或者在调用f时提供它:f.apply(someObjectThatNeedsToBecomeThisInFunc)
    • 所以如果func 是一个“方法”而不仅仅是一个简单的函数,这很有用。
    猜你喜欢
    • 2013-04-23
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多