throttle.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. export default (function (func, wait, options) {
  2. var timeout, context, args, result;
  3. var previous = 0;
  4. if (!options)
  5. options = {};
  6. var later = function () {
  7. previous = options.leading === false ? 0 : Date.now();
  8. timeout = null;
  9. result = func.apply(context, args);
  10. if (!timeout)
  11. context = args = null;
  12. };
  13. var throttled = function () {
  14. var now = Date.now();
  15. if (!previous && options.leading === false)
  16. previous = now;
  17. var remaining = wait - (now - previous);
  18. context = this;
  19. args = arguments;
  20. if (remaining <= 0 || remaining > wait) {
  21. if (timeout) {
  22. clearTimeout(timeout);
  23. timeout = null;
  24. }
  25. previous = now;
  26. result = func.apply(context, args);
  27. if (!timeout)
  28. context = args = null;
  29. }
  30. else if (!timeout && options.trailing !== false) {
  31. timeout = setTimeout(later, remaining);
  32. }
  33. return result;
  34. };
  35. throttled.cancel = function () {
  36. clearTimeout(timeout);
  37. previous = 0;
  38. timeout = context = args = null;
  39. };
  40. return throttled;
  41. });
  42. //# sourceMappingURL=throttle.js.map