【发布时间】: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