blob: 03a5ceaa753b62c4b98baedd196e5ba4662e81ed [file] [log] [blame]
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _apply = require("babel-runtime/core-js/reflect/apply");
var _apply2 = _interopRequireDefault(_apply);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Throttling enforces a maximum number of times a function can be called over time.
*
* @param callback the function to throttle
* @param delay optional delay, default to 1000/60ms
* @param context optional context of this, default to global window
* @returns {Function} reference to immediate and cancel functions
* @see https://developer.mozilla.org/en-US/docs/Web/Events/resize#Example
* @see https://gist.github.com/yoavniran/d1d33f278bb7744d55c3
* @see https://github.com/pelotoncycle/frame-throttle
* @see https://github.com/jeromedecoster/raf-funcs
*/
var MIN_DELAY = 1000 / 60;
var throttleFunction = function throttleFunction(callback) {
var delay = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : MIN_DELAY;
var context = arguments[2];
if (delay < MIN_DELAY) {
delay = MIN_DELAY;
}
if (!context) {
context = undefined || window;
}
var next = null;
var start = 0;
return function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var _cancel = function _cancel() {
if (next !== null) {
window.cancelAnimationFrame(next);
next = null;
}
};
var execute = function execute() {
_cancel();
return (0, _apply2.default)(callback, context, args);
};
var later = function later() {
if (delay - (Date.now() - start) <= 0) {
return execute();
}
next = window.requestAnimationFrame(later);
};
if (next === null) {
start = Date.now();
next = window.requestAnimationFrame(later);
}
return {
cancel: function cancel() {
return _cancel();
},
immediate: function immediate() {
return execute();
}
};
};
};
exports.default = throttleFunction;
module.exports = exports["default"];