Source: debounce/debounce.es.js

  1. /**
  2. * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
  3. *
  4. * This library is free software; you can redistribute it and/or modify it under
  5. * the terms of the GNU Lesser General Public License as published by the Free
  6. * Software Foundation; either version 2.1 of the License, or (at your option)
  7. * any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful, but WITHOUT
  10. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  11. * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
  12. * details.
  13. */
  14. /**
  15. * Debounces function execution.
  16. * @param {!function()} fn
  17. * @param {number} delay
  18. * @return {!function()}
  19. */
  20. function debounce(fn, delay) {
  21. return function debounced() {
  22. const args = arguments;
  23. cancelDebounce(debounced);
  24. debounced.id = setTimeout(() => {
  25. fn(...args);
  26. }, delay);
  27. };
  28. }
  29. /**
  30. * Cancels the scheduled debounced function.
  31. * @param {function()} debounced
  32. */
  33. function cancelDebounce(debounced) {
  34. clearTimeout(debounced.id);
  35. }
  36. export default debounce;
  37. export {cancelDebounce, debounce};