jquery-debounce-1.0.6.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /**
  2. * Debounce and throttle function's decorator plugin 1.0.5
  3. *
  4. * Copyright (c) 2009 Filatov Dmitry (alpha@zforms.ru)
  5. * Dual licensed under the MIT and GPL licenses:
  6. * http://www.opensource.org/licenses/mit-license.php
  7. * http://www.gnu.org/licenses/gpl.html
  8. *
  9. */
  10. (function($) {
  11. $.extend({
  12. debounce : function(fn, timeout, invokeAsap, ctx) {
  13. if(arguments.length == 3 && typeof invokeAsap != 'boolean') {
  14. ctx = invokeAsap;
  15. invokeAsap = false;
  16. }
  17. var timer;
  18. return function() {
  19. var args = arguments;
  20. ctx = ctx || this;
  21. invokeAsap && !timer && fn.apply(ctx, args);
  22. clearTimeout(timer);
  23. timer = setTimeout(function() {
  24. invokeAsap || fn.apply(ctx, args);
  25. timer = null;
  26. }, timeout);
  27. };
  28. },
  29. throttle : function(fn, timeout, ctx) {
  30. var timer, args, needInvoke;
  31. return function() {
  32. args = arguments;
  33. needInvoke = true;
  34. ctx = ctx || this;
  35. timer || (function() {
  36. if(needInvoke) {
  37. fn.apply(ctx, args);
  38. needInvoke = false;
  39. timer = setTimeout(arguments.callee, timeout);
  40. }
  41. else {
  42. timer = null;
  43. }
  44. })();
  45. };
  46. }
  47. });
  48. })(jQuery);