1 var isObject = require(
'./isObject'),
2 now = require(
'./now'),
3 toNumber = require(
'./toNumber');
6 var FUNC_ERROR_TEXT =
'Expected a function';
9 var nativeMax = Math.max,
66 function debounce(func, wait, options) {
78 if (typeof func !=
'function') {
79 throw new TypeError(FUNC_ERROR_TEXT);
81 wait = toNumber(wait) || 0;
82 if (isObject(options)) {
83 leading = !!options.leading;
84 maxing =
'maxWait' in options;
85 maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
86 trailing =
'trailing' in options ? !!options.trailing : trailing;
89 function invokeFunc(time) {
93 lastArgs = lastThis = undefined;
94 lastInvokeTime = time;
95 result = func.apply(thisArg, args);
99 function leadingEdge(time) {
101 lastInvokeTime = time;
103 timerId = setTimeout(timerExpired, wait);
105 return leading ? invokeFunc(time) : result;
108 function remainingWait(time) {
109 var timeSinceLastCall = time - lastCallTime,
110 timeSinceLastInvoke = time - lastInvokeTime,
111 result = wait - timeSinceLastCall;
113 return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;
116 function shouldInvoke(time) {
117 var timeSinceLastCall = time - lastCallTime,
118 timeSinceLastInvoke = time - lastInvokeTime;
123 return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
124 (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
127 function timerExpired() {
129 if (shouldInvoke(time)) {
130 return trailingEdge(time);
133 timerId = setTimeout(timerExpired, remainingWait(time));
136 function trailingEdge(time) {
141 if (trailing && lastArgs) {
142 return invokeFunc(time);
144 lastArgs = lastThis = undefined;
149 if (timerId !== undefined) {
150 clearTimeout(timerId);
153 lastArgs = lastCallTime = lastThis = timerId = undefined;
157 return timerId === undefined ? result : trailingEdge(now());
160 function debounced() {
162 isInvoking = shouldInvoke(time);
164 lastArgs = arguments;
169 if (timerId === undefined) {
170 return leadingEdge(lastCallTime);
174 timerId = setTimeout(timerExpired, wait);
175 return invokeFunc(lastCallTime);
178 if (timerId === undefined) {
179 timerId = setTimeout(timerExpired, wait);
183 debounced.cancel = cancel;
184 debounced.flush = flush;
188 module.exports = debounce;