UNPKG

ut2

Version:

一个现代 JavaScript 实用工具库。[点击查看在线文档]。

82 lines (78 loc) 2.79 kB
'use strict'; var defaultTo = require('../defaultTo.js'); var toNumber = require('../toNumber.js'); var helpers = require('./helpers.js'); var native = require('./native.js'); function baseDebounce(func, wait, immediate, __throttle__) { if (__throttle__ === void 0) { __throttle__ = false; } if (typeof func !== 'function') { throw new TypeError(helpers.FUNC_ERROR_TEXT); } var timer, lastCallTime, lastInvokeTime, lastArgs, lastThis, result; wait = defaultTo(toNumber(wait), 0); function shouldInvoke(time) { if (lastCallTime === native.nativeUndefined) { return true; } var timeSinceLastCall = time - lastCallTime; var timeSinceLastInvoke = time - lastInvokeTime; return timeSinceLastCall >= wait || timeSinceLastCall < 0 || (__throttle__ && timeSinceLastInvoke >= wait); } function invokeFunc(time) { lastInvokeTime = time; result = func.apply(lastThis, lastArgs); lastThis = lastArgs = native.nativeUndefined; return result; } function debounced() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } lastThis = this; lastArgs = args; var time = Date.now(); var isInvoke = shouldInvoke(time); var waitTime = !__throttle__ ? wait : !isInvoke && lastCallTime !== native.nativeUndefined && timer === native.nativeUndefined ? wait - (time - lastCallTime) : wait; lastCallTime = time; if (isInvoke) { if (immediate && timer === native.nativeUndefined) { return invokeFunc(time); } } if (timer !== native.nativeUndefined && !__throttle__) { clearTimeout(timer); timer = native.nativeUndefined; } if (timer === native.nativeUndefined) { timer = setTimeout(function () { timer = native.nativeUndefined; invokeFunc(Date.now()); }, waitTime); } return result; } function cancel() { if (timer !== native.nativeUndefined) { clearTimeout(timer); timer = native.nativeUndefined; } lastCallTime = timer = lastArgs = lastThis = native.nativeUndefined; } function flush() { if (timer !== native.nativeUndefined) { clearTimeout(timer); timer = native.nativeUndefined; return invokeFunc(Date.now()); } return result; } function pending() { return timer !== native.nativeUndefined; } debounced.cancel = cancel; debounced.flush = flush; debounced.pending = pending; return debounced; } module.exports = baseDebounce;