为什么超时变量在这种情况下可以共享?

时间:2016-08-03 02:35:17

标签: javascript scope closures settimeout debouncing

answers to this question中有人明智地指出

  

在每次调用时,超时变量都可以访问   即使在debounce本身已经返回之后产生了功能,并且可以   转换不同的电话。

这对我来说没有多大意义。由于超时变量是每次去抖动的本地变量,它不应该是可共享的,不是吗?

P.S。即使它是封闭的,每个调用都应该有一个不同的闭包,它们只是在母函数返回后同时延长它们的生命,但它们不应该相互通信,对吧?

以下是其他问题的功能:

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

1 个答案:

答案 0 :(得分: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以设置多个去抖动功能(上例中的gh)。