blob: 27f977c3454037d408c6eab9eda0bbc2c60d159c [file] [log] [blame]
Copybara botbe50d492023-11-30 00:16:42 +01001"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6
7var _apply = require("babel-runtime/core-js/reflect/apply");
8
9var _apply2 = _interopRequireDefault(_apply);
10
11function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12
13/**
14 * Debouncing enforces that a function not be called again until a certain
15 * amount of time has passed without it being called.
16 *
17 * @see https://css-tricks.com/the-difference-between-throttling-and-debouncing/
18 * @see https://github.com/webmodules/raf-debounce
19 * @see https://github.com/moszeed/es6-promise-debounce
20 * @see https://gist.github.com/philbirnie/893950093611d5c1dff4246a572cfbeb/
21 * @see https://github.com/SliceMeNice-ES6/event-utils/blob/master/debounce.js
22 * @see https://github.com/jeromedecoster/raf-funcs
23 * @see http://unscriptable.com/2009/03/20/debouncing-javascript-methods/
24 * @see http://davidwalsh.name/javascript-debounce-function
25 *
26 * @param callback the callback
27 * @param threshold optional delay, default to 250 ms, min to 1000/60ms ms
28 * @param context optional context of this, default to global
29 * @return {Function} reference to immediate and cancel
30 */
31var MIN_THRESHOLD = 1000 / 60;
32
33var debounceFunction = function debounceFunction(callback) {
34 var threshold = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 250;
35 var context = arguments[2];
36
37
38 if (threshold < MIN_THRESHOLD) {
39 threshold = MIN_THRESHOLD;
40 }
41
42 if (!context) {
43 context = this || window;
44 }
45
46 var next = null;
47 var start = 0;
48
49 return function () {
50 for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
51 args[_key] = arguments[_key];
52 }
53
54 var _cancel = function _cancel() {
55 if (next) {
56 window.cancelAnimationFrame(next);
57 next = null;
58 }
59 };
60
61 var execute = function execute() {
62 _cancel();
63 return (0, _apply2.default)(callback, context, args);
64 };
65
66 var later = function later() {
67 if (threshold - (Date.now() - start) <= 0) {
68 return execute();
69 }
70 next = window.requestAnimationFrame(later);
71 };
72
73 _cancel();
74 start = Date.now();
75 next = window.requestAnimationFrame(later);
76
77 return {
78 cancel: function cancel() {
79 return _cancel();
80 },
81 immediate: function immediate() {
82 return execute();
83 }
84 };
85 };
86};
87
88exports.default = debounceFunction;
89module.exports = exports["default"];