blob: 27f977c3454037d408c6eab9eda0bbc2c60d159c [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 }; }
/**
* Debouncing enforces that a function not be called again until a certain
* amount of time has passed without it being called.
*
* @see https://css-tricks.com/the-difference-between-throttling-and-debouncing/
* @see https://github.com/webmodules/raf-debounce
* @see https://github.com/moszeed/es6-promise-debounce
* @see https://gist.github.com/philbirnie/893950093611d5c1dff4246a572cfbeb/
* @see https://github.com/SliceMeNice-ES6/event-utils/blob/master/debounce.js
* @see https://github.com/jeromedecoster/raf-funcs
* @see http://unscriptable.com/2009/03/20/debouncing-javascript-methods/
* @see http://davidwalsh.name/javascript-debounce-function
*
* @param callback the callback
* @param threshold optional delay, default to 250 ms, min to 1000/60ms ms
* @param context optional context of this, default to global
* @return {Function} reference to immediate and cancel
*/
var MIN_THRESHOLD = 1000 / 60;
var debounceFunction = function debounceFunction(callback) {
var threshold = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 250;
var context = arguments[2];
if (threshold < MIN_THRESHOLD) {
threshold = MIN_THRESHOLD;
}
if (!context) {
context = this || 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) {
window.cancelAnimationFrame(next);
next = null;
}
};
var execute = function execute() {
_cancel();
return (0, _apply2.default)(callback, context, args);
};
var later = function later() {
if (threshold - (Date.now() - start) <= 0) {
return execute();
}
next = window.requestAnimationFrame(later);
};
_cancel();
start = Date.now();
next = window.requestAnimationFrame(later);
return {
cancel: function cancel() {
return _cancel();
},
immediate: function immediate() {
return execute();
}
};
};
};
exports.default = debounceFunction;
module.exports = exports["default"];