在这个问题的答案中,有人明智地指出
即使在 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?
};
};