debounce.js 795 B

1234567891011121314151617181920212223242526272829303132
  1. /**
  2. * Debounce callback execution
  3. */
  4. function debounce(fn, threshold, isAsap){
  5. var timeout, result;
  6. function debounced(){
  7. var args = arguments, context = this;
  8. function delayed(){
  9. if (! isAsap) {
  10. result = fn.apply(context, args);
  11. }
  12. timeout = null;
  13. }
  14. if (timeout) {
  15. clearTimeout(timeout);
  16. } else if (isAsap) {
  17. result = fn.apply(context, args);
  18. }
  19. timeout = setTimeout(delayed, threshold);
  20. return result;
  21. }
  22. debounced.cancel = function(){
  23. clearTimeout(timeout);
  24. };
  25. return debounced;
  26. }
  27. module.exports = debounce;