index.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /**
  2. * Returns a function, that, as long as it continues to be invoked, will not
  3. * be triggered. The function will be called after it stops being called for
  4. * N milliseconds. If `immediate` is passed, trigger the function on the
  5. * leading edge, instead of the trailing. The function also has a property 'clear'
  6. * that is a function which will clear the timer to prevent previously scheduled executions.
  7. *
  8. * @source underscore.js
  9. * @see http://unscriptable.com/2009/03/20/debouncing-javascript-methods/
  10. * @param {Function} function to wrap
  11. * @param {Number} timeout in ms (`100`)
  12. * @param {Boolean} whether to execute at the beginning (`false`)
  13. * @api public
  14. */
  15. function debounce(func, wait, immediate){
  16. var timeout, args, context, timestamp, result;
  17. if (null == wait) wait = 100;
  18. function later() {
  19. var last = Date.now() - timestamp;
  20. if (last < wait && last >= 0) {
  21. timeout = setTimeout(later, wait - last);
  22. } else {
  23. timeout = null;
  24. if (!immediate) {
  25. result = func.apply(context, args);
  26. context = args = null;
  27. }
  28. }
  29. };
  30. var debounced = function(){
  31. context = this;
  32. args = arguments;
  33. timestamp = Date.now();
  34. var callNow = immediate && !timeout;
  35. if (!timeout) timeout = setTimeout(later, wait);
  36. if (callNow) {
  37. result = func.apply(context, args);
  38. context = args = null;
  39. }
  40. return result;
  41. };
  42. debounced.clear = function() {
  43. if (timeout) {
  44. clearTimeout(timeout);
  45. timeout = null;
  46. }
  47. };
  48. debounced.flush = function() {
  49. if (timeout) {
  50. result = func.apply(context, args);
  51. context = args = null;
  52. clearTimeout(timeout);
  53. timeout = null;
  54. }
  55. };
  56. return debounced;
  57. };
  58. // Adds compatibility for ES modules
  59. debounce.debounce = debounce;
  60. module.exports = debounce;