diff --git a/README.md b/README.md index 13648d57b..49895db9e 100644 --- a/README.md +++ b/README.md @@ -240,6 +240,7 @@ average(1, 2, 3); * [`partialRight`](#partialright) * [`runPromisesInSeries`](#runpromisesinseries) * [`sleep`](#sleep) +* [`throttle`](#throttle) * [`times`](#times) * [`unfold`](#unfold) @@ -4047,6 +4048,56 @@ async function sleepyWork() {
[⬆ Back to top](#table-of-contents) +### throttle + +Creates a throttled function that only invokes the provided function at most once per every `wait` milliseconds + +Use `setTimeout()` and `clearTimeout()` to throttle the given method, `fn`. +Use `Function.apply()` to apply the `this` context to the function and provide the necessary `arguments`. +Use `Date.now()` to keep track of the last time the throttled function was invoked. +Omit the second argument, `wait`, to set the timeout at a default of 0 ms. + +```js +const throttle = (fn, wait) => { + let inThrottle, lastFn, lastTime; + return function() { + const context = this, + args = arguments; + if (!inThrottle) { + fn.apply(context, args); + lastTime = Date.now(); + inThrottle = true; + } else { + clearTimeout(lastFn); + lastFn = setTimeout(function() { + if (Date.now() - lastTime >= wait) { + fn.apply(context, args); + lastTime = Date.now(); + } + }, wait - (Date.now() - lastTime)); + } + }; +}; +``` + +
+Examples + +```js +window.addEventListener( + 'resize', + throttle(function(evt) { + console.log(window.innerWidth); + console.log(window.innerHeight); + }, 250) +); // Will log the window dimensions at most every 250ms +``` + +
+ +
[⬆ Back to top](#table-of-contents) + + ### times Iterates over a callback `n` times diff --git a/docs/index.html b/docs/index.html index e1f6a069e..a14acc8f7 100644 --- a/docs/index.html +++ b/docs/index.html @@ -50,7 +50,7 @@ scrollToTop(); } }, false); - }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Adapter

ary

Creates a function that accepts up to n arguments, ignoring any additional arguments.

Call the provided function, fn, with up to n arguments, using Array.slice(0,n) and the spread operator (...).

const ary = (fn, n) => (...args) => fn(...args.slice(0, n));
+      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Adapter

ary

Creates a function that accepts up to n arguments, ignoring any additional arguments.

Call the provided function, fn, with up to n arguments, using Array.slice(0,n) and the spread operator (...).

const ary = (fn, n) => (...args) => fn(...args.slice(0, n));
 
const firstTwoMax = ary(Math.max, 2);
 [[2, 6, 'a'], [8, 4, 6], [10]].map(x => firstTwoMax(...x)); // [6, 8, 10]
 

call

Given a key and a set of arguments, call them when given a context. Primarily useful in composition.

Use a closure to call a stored key with stored arguments.

const call = (key, ...args) => context => context[key](...args);
@@ -927,6 +927,33 @@ document.bodyawait sleep(1000);
   console.log('I woke up after 1 second.');
 }
+

throttle

Creates a throttled function that only invokes the provided function at most once per every wait milliseconds

Use setTimeout() and clearTimeout() to throttle the given method, fn. Use Function.apply() to apply the this context to the function and provide the necessary arguments. Use Date.now() to keep track of the last time the throttled function was invoked. Omit the second argument, wait, to set the timeout at a default of 0 ms.

const throttle = (fn, wait) => {
+  let inThrottle, lastFn, lastTime;
+  return function() {
+    const context = this,
+      args = arguments;
+    if (!inThrottle) {
+      fn.apply(context, args);
+      lastTime = Date.now();
+      inThrottle = true;
+    } else {
+      clearTimeout(lastFn);
+      lastFn = setTimeout(function() {
+        if (Date.now() - lastTime >= wait) {
+          fn.apply(context, args);
+          lastTime = Date.now();
+        }
+      }, wait - (Date.now() - lastTime));
+    }
+  };
+};
+
window.addEventListener(
+  'resize',
+  throttle(function(evt) {
+    console.log(window.innerWidth);
+    console.log(window.innerHeight);
+  }, 250)
+); // Will log the window dimensions at most every 250ms
 

times

Iterates over a callback n times

Use Function.call() to call fn n times or until it returns false. Omit the last argument, context, to use an undefined object (or the global object in non-strict mode).

const times = (n, fn, context = undefined) => {
   let i = 0;
   while (fn.call(context, i) !== false && ++i < n) {}