在界面中添加一个按钮。immediate设置为false,wait设置为1000.连点两下按钮,later函数会被调用。这是为啥呢?我设置的超时时间为1000,还没到时间呢,为啥later会被触发执行呢?
underscore这个库的防抖函数实现如下。
var timeout, previous, args, result, context;
var later = function () {
var passed = now() - previous;
console.log('passed', passed)
if (passed < wait) {
console.log('later被调用,但是还有' + (wait - passed) + "时间,才能调用")
timeout = setTimeout(later, wait - passed);
} else {
console.log('clear timeout and call our func')
timeout = null;
if (!immediate) result = func.apply(context, args);
// This check is needed because `func` can recursively invoke `debounced`.
if (!timeout) args = context = null;
}
};
var debounced = restArguments(function (_args) {
context = this;
args = _args;
previous = now();
console.log('debounce timeout', timeout)
if (!timeout) {
console.log('------------')
timeout = setTimeout(later, wait);
if (immediate) result = func.apply(context, args);
}
return result;
});
这样连点两次,test在不到1秒的时候,就会执行。为什么呢?