debounce.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /**
  2. * angular-strap
  3. * @version v2.3.9 - 2016-06-10
  4. * @link http://mgcrea.github.io/angular-strap
  5. * @author Olivier Louvignes <olivier@mg-crea.com> (https://github.com/mgcrea)
  6. * @license MIT License, http://www.opensource.org/licenses/MIT
  7. */
  8. 'use strict';
  9. angular.module('mgcrea.ngStrap.helpers.debounce', []).factory('debounce', [ '$timeout', function($timeout) {
  10. return function(func, wait, immediate) {
  11. var timeout = null;
  12. return function() {
  13. var context = this;
  14. var args = arguments;
  15. var callNow = immediate && !timeout;
  16. if (timeout) {
  17. $timeout.cancel(timeout);
  18. }
  19. timeout = $timeout(function later() {
  20. timeout = null;
  21. if (!immediate) {
  22. func.apply(context, args);
  23. }
  24. }, wait, false);
  25. if (callNow) {
  26. func.apply(context, args);
  27. }
  28. return timeout;
  29. };
  30. };
  31. } ]).factory('throttle', [ '$timeout', function($timeout) {
  32. return function(func, wait, options) {
  33. var timeout = null;
  34. if (!options) options = {};
  35. return function() {
  36. var context = this;
  37. var args = arguments;
  38. if (!timeout) {
  39. if (options.leading !== false) {
  40. func.apply(context, args);
  41. }
  42. timeout = $timeout(function later() {
  43. timeout = null;
  44. if (options.trailing !== false) {
  45. func.apply(context, args);
  46. }
  47. }, wait, false);
  48. }
  49. };
  50. };
  51. } ]);