once.js 1002 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // It's actually "debounce"
  2. "use strict";
  3. var isValue = require("es5-ext/object/is-value")
  4. , callable = require("es5-ext/object/valid-callable")
  5. , nextTick = require("next-tick")
  6. , validTimeout = require("./valid-timeout");
  7. var apply = Function.prototype.apply;
  8. module.exports = function (fn/*, timeout*/) {
  9. var scheduled, run, context, args, delay, timeout = arguments[1], handle;
  10. callable(fn);
  11. if (isValue(timeout)) {
  12. timeout = validTimeout(timeout);
  13. delay = setTimeout;
  14. } else {
  15. delay = nextTick;
  16. }
  17. run = function () {
  18. if (!scheduled) return; // IE8 tends to not clear immediate timeouts properly
  19. scheduled = false;
  20. handle = null;
  21. apply.call(fn, context, args);
  22. context = null;
  23. args = null;
  24. };
  25. return function () {
  26. if (scheduled) {
  27. if (!isValue(handle)) {
  28. // 'nextTick' based, no room for debounce
  29. return;
  30. }
  31. clearTimeout(handle);
  32. }
  33. scheduled = true;
  34. context = this;
  35. args = arguments;
  36. handle = delay(run, timeout);
  37. };
  38. };