debounce.js 1.3 KB

12345678910111213141516171819202122
  1. /* eslint-disable no-undefined */
  2. var throttle = require('./throttle');
  3. /**
  4. * Debounce execution of a function. Debouncing, unlike throttling,
  5. * guarantees that a function is only executed a single time, either at the
  6. * very beginning of a series of calls, or at the very end.
  7. *
  8. * @param {Number} delay A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful.
  9. * @param {Boolean} [atBegin] Optional, defaults to false. If atBegin is false or unspecified, callback will only be executed `delay` milliseconds
  10. * after the last debounced-function call. If atBegin is true, callback will be executed only at the first debounced-function call.
  11. * (After the throttled-function has not been called for `delay` milliseconds, the internal counter is reset).
  12. * @param {Function} callback A function to be executed after delay milliseconds. The `this` context and all arguments are passed through, as-is,
  13. * to `callback` when the debounced-function is executed.
  14. *
  15. * @return {Function} A new, debounced function.
  16. */
  17. module.exports = function ( delay, atBegin, callback ) {
  18. return callback === undefined ? throttle(delay, atBegin, false) : throttle(delay, callback, atBegin !== false);
  19. };