jquery-debounce-1.0.5.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. if(!timer) {
  36. (function() {
  37. if(needInvoke) {
  38. fn.apply(ctx, args);
  39. needInvoke = false;
  40. timer = setTimeout(arguments.callee, timeout);
  41. }
  42. else {
  43. timer = null;
  44. }
  45. })();
  46. }
  47. };
  48. }
  49. });
  50. })(jQuery);