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

debounce.js 1018B

12345678910111213141516171819202122232425262728293031323334353637
  1. var restArguments = require('./restArguments.js');
  2. var delay = require('./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. 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. }
  30. module.exports = debounce;