diff --git a/lodash.js b/lodash.js index 145bf6b6c..3c74ce1b8 100644 --- a/lodash.js +++ b/lodash.js @@ -5433,37 +5433,36 @@ */ function debounce(func, wait, options) { var args, + maxTimeoutId, result, stamp, thisArg, - callCount = 0, + timeoutId, + trailingCall, lastCalled = 0, maxWait = false, - maxTimeoutId = null, - timeoutId = null, trailing = true; if (!isFunction(func)) { throw new TypeError; } - wait = nativeMax(0, wait || 0); + wait = nativeMax(0, wait) || 0; if (options === true) { var leading = true; trailing = false; } else if (isObject(options)) { leading = options.leading; - maxWait = 'maxWait' in options && nativeMax(wait, options.maxWait || 0); + maxWait = 'maxWait' in options && (nativeMax(wait, options.maxWait) || 0); trailing = 'trailing' in options ? options.trailing : trailing; } var delayed = function() { var remaining = wait - (new Date - stamp); if (remaining <= 0) { - var isCalled = trailing && (!leading || callCount > 1); if (maxTimeoutId) { clearTimeout(maxTimeoutId); } - callCount = 0; - maxTimeoutId = timeoutId = null; + var isCalled = trailingCall; + maxTimeoutId = timeoutId = trailingCall = undefined; if (isCalled) { lastCalled = +new Date; result = func.apply(thisArg, args); @@ -5477,8 +5476,7 @@ if (timeoutId) { clearTimeout(timeoutId); } - callCount = 0; - maxTimeoutId = timeoutId = null; + maxTimeoutId = timeoutId = trailingCall = undefined; if (trailing || (maxWait !== wait)) { lastCalled = +new Date; result = func.apply(thisArg, args); @@ -5489,21 +5487,16 @@ args = arguments; stamp = +new Date; thisArg = this; - callCount++; + trailingCall = trailing && (timeoutId || !leading); - if (maxWait === false) { - if (leading && callCount < 2) { - result = func.apply(thisArg, args); - } - } else { + if (maxWait !== false) { if (!maxTimeoutId && !leading) { lastCalled = stamp; } var remaining = maxWait - (stamp - lastCalled); if (remaining <= 0) { if (maxTimeoutId) { - clearTimeout(maxTimeoutId); - maxTimeoutId = null; + maxTimeoutId = clearTimeout(maxTimeoutId); } lastCalled = stamp; result = func.apply(thisArg, args); @@ -5512,6 +5505,9 @@ maxTimeoutId = setTimeout(maxDelayed, remaining); } } + else if (leading && !timeoutId) { + result = func.apply(thisArg, args); + } if (!timeoutId && wait !== maxWait) { timeoutId = setTimeout(delayed, wait); }