debounce.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /**
  2. * angular-strap
  3. * @version v2.3.5 - 2015-10-29
  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, args = arguments, callNow = immediate && !timeout;
  14. if (timeout) {
  15. $timeout.cancel(timeout);
  16. }
  17. timeout = $timeout(function later() {
  18. timeout = null;
  19. if (!immediate) {
  20. func.apply(context, args);
  21. }
  22. }, wait, false);
  23. if (callNow) {
  24. func.apply(context, args);
  25. }
  26. return timeout;
  27. };
  28. };
  29. } ]).factory('throttle', [ '$timeout', function($timeout) {
  30. return function(func, wait, options) {
  31. var timeout = null;
  32. options || (options = {});
  33. return function() {
  34. var context = this, args = arguments;
  35. if (!timeout) {
  36. if (options.leading !== false) {
  37. func.apply(context, args);
  38. }
  39. timeout = $timeout(function later() {
  40. timeout = null;
  41. if (options.trailing !== false) {
  42. func.apply(context, args);
  43. }
  44. }, wait, false);
  45. }
  46. };
  47. };
  48. } ]);