0

这个问题的答案中,有人明智地指出

即使在 debounce 本身返回后,timeout 变量在每次调用生成的函数期间仍可访问,并且可以在不同的调用中更改。

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

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

这是另一个问题的功能:

// 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?
     }; 
};
4

1 回答 1

2

是的,每次调用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多次调用自身来设置多个去抖动函数(agh在上面的示例中)。

于 2016-08-03T02:39:37.913 回答