Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

debounce.js 999B

1234567891011121314151617181920212223242526272829303132333435
  1. import restArguments from './restArguments.js';
  2. import delay from './delay.js';
  3. // When a sequence of calls of the returned function ends, the argument
  4. // function is triggered. The end of a sequence is defined by the `wait`
  5. // parameter. If `immediate` is passed, the argument function will be
  6. // triggered at the beginning of the sequence instead of at the end.
  7. export default function debounce(func, wait, immediate) {
  8. var timeout, result;
  9. var later = function(context, args) {
  10. timeout = null;
  11. if (args) result = func.apply(context, args);
  12. };
  13. var debounced = restArguments(function(args) {
  14. if (timeout) clearTimeout(timeout);
  15. if (immediate) {
  16. var callNow = !timeout;
  17. timeout = setTimeout(later, wait);
  18. if (callNow) result = func.apply(this, args);
  19. } else {
  20. timeout = delay(later, wait, this, args);
  21. }
  22. return result;
  23. });
  24. debounced.cancel = function() {
  25. clearTimeout(timeout);
  26. timeout = null;
  27. };
  28. return debounced;
  29. }