You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
1.7 KiB

6 months ago
  1. # debounce
  2. Useful for implementing behavior that should only happen after a repeated
  3. action has completed.
  4. ## Installation
  5. $ component install component/debounce
  6. Or in node:
  7. $ npm install debounce
  8. ## Example
  9. ```js
  10. var debounce = require('debounce');
  11. window.onresize = debounce(resize, 200);
  12. function resize(e) {
  13. console.log('height', window.innerHeight);
  14. console.log('width', window.innerWidth);
  15. }
  16. ```
  17. To later clear the timer and cancel currently scheduled executions:
  18. ```
  19. window.onresize.clear();
  20. ```
  21. To execute any pending invocations and reset the timer:
  22. ```
  23. window.onresize.flush();
  24. ```
  25. Alternately, if using newer syntax:
  26. ```js
  27. import { debounce } from "debounce";
  28. ```
  29. ## API
  30. ### debounce(fn, wait, [ immediate || false ])
  31. Creates and returns a new debounced version of the passed function that
  32. will postpone its execution until after wait milliseconds have elapsed
  33. since the last time it was invoked.
  34. Pass `true` for the `immediate` parameter to cause debounce to trigger
  35. the function on the leading edge instead of the trailing edge of the wait
  36. interval. Useful in circumstances like preventing accidental double-clicks
  37. on a "submit" button from firing a second time.
  38. The debounced function returned has a property 'clear' that is a
  39. function that will clear any scheduled future executions of your function.
  40. The debounced function returned has a property 'flush' that is a
  41. function that will immediately execute the function if and only if execution is scheduled,
  42. and reset the execution timer for subsequent invocations of the debounced
  43. function.
  44. ## License
  45. MIT
  46. Original implementation is from [`underscore.js`](http://underscorejs.org/)
  47. which also has an MIT license.