Browse Source

[function.debounce]: add function

mightyplow 7 years ago
parent
commit
df39376431
3 changed files with 27 additions and 0 deletions
  1. 25 0
      src/function/debounce.js
  2. 1 0
      src/function/index.js
  3. 1 0
      src/index.js

+ 25 - 0
src/function/debounce.js

@@ -0,0 +1,25 @@
+/**
+ * Creates a function which debounces with the given timeout and resets the timer
+ * on every function call.
+ *
+ * The returned debounced function has a function property abort() which aborts the timer.
+ *
+ * @memberOf function
+ * @function
+ * @param {function} fn
+ * @param {number} timeout
+ * @return {function(...[*])}
+ */
+export default (fn, timeout = 0) => {
+    let timer = null;
+    const abortTimer = () => clearTimeout(timer);
+
+    const debouncedFunction = (...args) => {
+        abortTimer();
+        timer = setTimeout(() => fn(...args), timeout)
+    };
+
+    debouncedFunction.abort = abortTimer;
+
+    return debouncedFunction;
+};

+ 1 - 0
src/function/index.js

@@ -5,6 +5,7 @@ export { default as argsToArray } from './argsToArray';
 export { default as checkTypes } from './checkTypes';
 export { default as combine } from './combine';
 export { default as curry } from './curry';
+export { default as debounce } from './debounce';
 export { default as enqueue } from './enqueue';
 export { default as enqueueWithResults } from './enqueueWithResults';
 export { default as identity } from './identity';

+ 1 - 0
src/index.js

@@ -14,6 +14,7 @@ export {
     checkTypes,
     combine,
     curry,
+    debounce,
     enqueueWithResults,
     enqueue,
     identity,