throttleByAnimationFrame.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
  2. import raf from './raf';
  3. export default function throttleByAnimationFrame(fn) {
  4. var requestId;
  5. var later = function later(args) {
  6. return function () {
  7. requestId = null;
  8. fn.apply(void 0, _toConsumableArray(args));
  9. };
  10. };
  11. var throttled = function throttled() {
  12. if (requestId == null) {
  13. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  14. args[_key] = arguments[_key];
  15. }
  16. requestId = raf(later(args));
  17. }
  18. };
  19. throttled.cancel = function () {
  20. return raf.cancel(requestId);
  21. };
  22. return throttled;
  23. }
  24. export function throttleByAnimationFrameDecorator() {
  25. // eslint-disable-next-line func-names
  26. return function (target, key, descriptor) {
  27. var fn = descriptor.value;
  28. var definingProperty = false;
  29. return {
  30. configurable: true,
  31. get: function get() {
  32. // eslint-disable-next-line no-prototype-builtins
  33. if (definingProperty || this === target.prototype || this.hasOwnProperty(key)) {
  34. return fn;
  35. }
  36. var boundFn = throttleByAnimationFrame(fn.bind(this));
  37. definingProperty = true;
  38. Object.defineProperty(this, key, {
  39. value: boundFn,
  40. configurable: true,
  41. writable: true
  42. });
  43. definingProperty = false;
  44. return boundFn;
  45. }
  46. };
  47. };
  48. }