throttle.js 727 B

123456789101112131415161718192021222324252627282930313233
  1. "use strict";
  2. var callable = require("es5-ext/object/valid-callable")
  3. , validTimeout = require("./valid-timeout")
  4. , apply = Function.prototype.apply;
  5. module.exports = function (fn, timeout) {
  6. var isScheduled = false, context, args, run;
  7. callable(fn);
  8. timeout = validTimeout(timeout);
  9. run = function () {
  10. var currentContext = context, currentArgs = args;
  11. if (!args) {
  12. isScheduled = false;
  13. return;
  14. }
  15. context = null;
  16. args = null;
  17. setTimeout(run, timeout);
  18. apply.call(fn, currentContext, currentArgs);
  19. };
  20. return function () {
  21. if (isScheduled) {
  22. context = this;
  23. args = arguments;
  24. return;
  25. }
  26. isScheduled = true;
  27. setTimeout(run, timeout);
  28. apply.call(fn, this, arguments);
  29. };
  30. };