Copybara bot | be50d49 | 2023-11-30 00:16:42 +0100 | [diff] [blame] | 1 | "use strict"; |
| 2 | |
| 3 | Object.defineProperty(exports, "__esModule", { |
| 4 | value: true |
| 5 | }); |
| 6 | |
| 7 | var _apply = require("babel-runtime/core-js/reflect/apply"); |
| 8 | |
| 9 | var _apply2 = _interopRequireDefault(_apply); |
| 10 | |
| 11 | function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } |
| 12 | |
| 13 | /** |
| 14 | * Throttling enforces a maximum number of times a function can be called over time. |
| 15 | * |
| 16 | * @param callback the function to throttle |
| 17 | * @param delay optional delay, default to 1000/60ms |
| 18 | * @param context optional context of this, default to global window |
| 19 | * @returns {Function} reference to immediate and cancel functions |
| 20 | * @see https://developer.mozilla.org/en-US/docs/Web/Events/resize#Example |
| 21 | * @see https://gist.github.com/yoavniran/d1d33f278bb7744d55c3 |
| 22 | * @see https://github.com/pelotoncycle/frame-throttle |
| 23 | * @see https://github.com/jeromedecoster/raf-funcs |
| 24 | */ |
| 25 | var MIN_DELAY = 1000 / 60; |
| 26 | |
| 27 | var throttleFunction = function throttleFunction(callback) { |
| 28 | var delay = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : MIN_DELAY; |
| 29 | var context = arguments[2]; |
| 30 | |
| 31 | |
| 32 | if (delay < MIN_DELAY) { |
| 33 | delay = MIN_DELAY; |
| 34 | } |
| 35 | |
| 36 | if (!context) { |
| 37 | context = undefined || window; |
| 38 | } |
| 39 | |
| 40 | var next = null; |
| 41 | var start = 0; |
| 42 | |
| 43 | return function () { |
| 44 | for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { |
| 45 | args[_key] = arguments[_key]; |
| 46 | } |
| 47 | |
| 48 | var _cancel = function _cancel() { |
| 49 | if (next !== null) { |
| 50 | window.cancelAnimationFrame(next); |
| 51 | next = null; |
| 52 | } |
| 53 | }; |
| 54 | |
| 55 | var execute = function execute() { |
| 56 | _cancel(); |
| 57 | return (0, _apply2.default)(callback, context, args); |
| 58 | }; |
| 59 | |
| 60 | var later = function later() { |
| 61 | if (delay - (Date.now() - start) <= 0) { |
| 62 | return execute(); |
| 63 | } |
| 64 | next = window.requestAnimationFrame(later); |
| 65 | }; |
| 66 | |
| 67 | if (next === null) { |
| 68 | start = Date.now(); |
| 69 | next = window.requestAnimationFrame(later); |
| 70 | } |
| 71 | |
| 72 | return { |
| 73 | cancel: function cancel() { |
| 74 | return _cancel(); |
| 75 | }, |
| 76 | immediate: function immediate() { |
| 77 | return execute(); |
| 78 | } |
| 79 | }; |
| 80 | }; |
| 81 | }; |
| 82 | |
| 83 | exports.default = throttleFunction; |
| 84 | module.exports = exports["default"]; |