debounceCore.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. "use strict";
  2. /**
  3. * Copyright (c) 2013-present, Facebook, Inc.
  4. *
  5. * This source code is licensed under the MIT license found in the
  6. * LICENSE file in the root directory of this source tree.
  7. *
  8. * @typechecks
  9. */
  10. /**
  11. * Invokes the given callback after a specified number of milliseconds have
  12. * elapsed, ignoring subsequent calls.
  13. *
  14. * For example, if you wanted to update a preview after the user stops typing
  15. * you could do the following:
  16. *
  17. * elem.addEventListener('keyup', debounce(this.updatePreview, 250), false);
  18. *
  19. * The returned function has a reset method which can be called to cancel a
  20. * pending invocation.
  21. *
  22. * var debouncedUpdatePreview = debounce(this.updatePreview, 250);
  23. * elem.addEventListener('keyup', debouncedUpdatePreview, false);
  24. *
  25. * // later, to cancel pending calls
  26. * debouncedUpdatePreview.reset();
  27. *
  28. * @param {function} func - the function to debounce
  29. * @param {number} wait - how long to wait in milliseconds
  30. * @param {*} context - optional context to invoke the function in
  31. * @param {?function} setTimeoutFunc - an implementation of setTimeout
  32. * if nothing is passed in the default setTimeout function is used
  33. * @param {?function} clearTimeoutFunc - an implementation of clearTimeout
  34. * if nothing is passed in the default clearTimeout function is used
  35. */
  36. function debounce(func, wait, context, setTimeoutFunc, clearTimeoutFunc) {
  37. setTimeoutFunc = setTimeoutFunc || setTimeout;
  38. clearTimeoutFunc = clearTimeoutFunc || clearTimeout;
  39. var timeout;
  40. function debouncer() {
  41. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  42. args[_key] = arguments[_key];
  43. }
  44. debouncer.reset();
  45. var callback = function callback() {
  46. func.apply(context, args);
  47. };
  48. callback.__SMmeta = func.__SMmeta;
  49. timeout = setTimeoutFunc(callback, wait);
  50. }
  51. debouncer.reset = function () {
  52. clearTimeoutFunc(timeout);
  53. };
  54. return debouncer;
  55. }
  56. module.exports = debounce;