-
-
Save beaucharman/e46b8e4d03ef30480d7f4db5a78498ca to your computer and use it in GitHub Desktop.
function throttle(callback, wait, immediate = false) { | |
let timeout = null | |
let initialCall = true | |
return function() { | |
const callNow = immediate && initialCall | |
const next = () => { | |
callback.apply(this, arguments) | |
timeout = null | |
} | |
if (callNow) { | |
initialCall = false | |
next() | |
} | |
if (!timeout) { | |
timeout = setTimeout(next, wait) | |
} | |
} | |
} | |
/** | |
* Normal event | |
* event | | | | |
* time ---------------- | |
* callback | | | | |
* | |
* Call search at most once per 300ms while keydown | |
* keydown | | | | | |
* time ----------------- | |
* search | | | |
* |300| |300| | |
*/ | |
const input = document.getElementById('id') | |
const handleKeydown = throttle((arg, event) => { | |
console.log(`${event.type} for ${arg} has the value of: ${event.target.value}`) | |
}, 300) | |
input.addEventListener('keydown', (event) => { | |
handleKeydown('input', event) | |
}) |
Nice implementation. You can also avoid leaning on arguments
in ES6:
return (...args) => {
if (!timeout) {
callbackArgs = args;
timeout = setTimeout(later, wait);
}
};
Very nice
In the correct implementation, the first call of the function occurs immediately. The next call, if less than the delay time passed, is ignored, but if it is the last, then a call occurs. Yours gist implements delay. Maybe you wanted to implement debounce?
function debounce(callback, delay) {
var timer = null;
return function() {
if (timer) return;
callback.apply(this, arguments);
timer = setTimeout(() => timer = null, delay);
}
}
Here is throttle function:
function throttle(callback, delay) {
let isThrottled = false, args, context;
function wrapper() {
if (isThrottled) {
args = arguments;
context = this;
return;
}
isThrottled = true;
callback.apply(this, arguments);
setTimeout(() => {
isThrottled = false;
if (args) {
wrapper.apply(context, args);
args = context = null;
}
}, delay);
}
return wrapper;
}
And to see the difference:
let logger = console.log;
let dlogger = debounce(logger, 5000);
dlogger(1); //log 1
dlogger(2); //ignore
dlogger(3); //ignore
setTimeout(() => dlogger(4), 5000) //log 4
let tlogger = throttle(logger, 5000);
tlogger(1); //log 1
tlogger(2); //ignore
setTimeout(() => tlogger(3), 5000) //log 3
tlogger(4); //last call waits 5 second and then log 4
let ylogger = yours_throttle(logger, 5000);
tlogger(1); //waits 5 second and then log 1
tlogger(2); //ignore
tlogger(3); //ignore
I made a variation of these patterns, for throttling promise returning functions, in the context of toggling the state of something and causing mutation requests to be sent over the network. This is to wrap the event handler, such that if a user clicks the action twice in fast succession, only the first is responded to and the second is considered a mistake. And, if they clicked by mistake to begin with, and click once more to undo slightly later, it queues the reverse/undo action to be sent, once the first action succeeds.
import promiseLimit from "promise-limit";
function throttleFirstTimeout(fn, window) {
let isThrottled = false;
let promise = null;
function wrapper() {
if (isThrottled) {
return promise;
}
isThrottled = true;
setTimeout(() => {
isThrottled = false;
promise = null;
}, window);
promise = fn();
return promise;
}
return wrapper;
}
function throttleFirstNow(fn, window) {
let promise = null;
let last = 0;
function wrapper() {
const now = Date.now();
if (last !== 0 && now - last < window) {
return promise;
}
last = now;
promise = null;
promise = fn();
return promise;
}
return wrapper;
}
function throttleLimit(fn, concurrency, window) {
const limited = promiseLimit(concurrency);
function throttleFn() {
return limited(fn);
}
return throttleFirstNow(throttleFn, window);
}
let i = 0;
function testPromiseReturningFunction(networkTime = 600) {
return new Promise(resolve => setTimeout(() => resolve(i++), networkTime));
}
const throttled = throttleLimit(testPromiseReturningFunction, 1, 500);
const test = () =>
throttled().then(j => console.log(j, new Date().getMilliseconds()));
test();
test();
setTimeout(test, 100);
setTimeout(test, 200);
setTimeout(test, 600);
setTimeout(test, 700);
Test example:
https://www.webpackbin.com/bins/-L0JghsIOjutzhCxmkqB
Thanks! This is the only implementation I could find that worked out-of-the-box. Great stuff!
I think you can move the definition of next
into throttle
- it won't be needlessly redefined on each call that way.
Made typescript (and a little simpler/more efficient) variation of debounce (!) function (without immediate call).
Hopefully someone finds it useful 😄
const throttle = <T extends []> (
callback: (..._: T) => void,
wait: number
): (..._: T) => void => {
const next = () => {
timeout = clearTimeout(timeout) as undefined;
callback(...lastArgs);
};
let timeout: NodeJS.Timeout | undefined;
let lastArgs: T;
return (...args: T) => {
lastArgs = args;
if (timeout === void 0) {
timeout = setTimeout(next, wait);
}
};
};
This isn't a throttle, it's a debounce.
💯
The author has duly noted the definition: Throttling enforces a maximum number of times a function can be called over time
But in the code example, the throttle
function doesn't accept any params for setting the maximum number of times.
In his example, execute this function at most once every 100 milliseconds
throttle should receive:
throttle(callback, 1, 100);
// callback => function to throttle
// 1 => at most once
// 100 => interval for this rate-limiting.
Similarly, for execute this function at most twice every 500 milliseconds
throttle(callback, 2, 500);
In fact, what author has provided is really a debounce function.
It appears there are varying opinions on throttle
functionality. 😄
My version of throttle
should:
- execute immediately the first time it's invoked, unlike
debounce
, which waits until its idle time is exceeded before initially executing. result: immediate visual feedback - not execute if invoked again before the wait time has been exceeded. result: reduce jank
- queue the latest denied execution to be re-invoked if possible when the wait time has been exceeded. result: ensure final invocation occurs
const throttle = (fn, wait) => {
let previouslyRun, queuedToRun;
return function invokeFn(...args) {
const now = Date.now();
queuedToRun = clearTimeout(queuedToRun);
if (!previouslyRun || (now - previouslyRun >= wait)) {
fn.apply(null, args);
previouslyRun = now;
} else {
queuedToRun = setTimeout(invokeFn.bind(null, ...args), wait - (now - previouslyRun));
}
}
};
const test = throttle(wait => { console.log(`INVOKED (${wait})`, Date.now()) }, 100);
for(let i = 0, wait = 0; i < 20; i++) {
wait += 30;
setTimeout(() => { test(wait); }, wait)
}
It appears there are varying opinions on
throttle
functionality. 😄
Right. Your solution also appears to be a throttle. The author's solution, however, appears purely a debounce.
To throttle a function means to ensure that the function is called at most once in a specified time period (for instance, once every 5 seconds).
function throttle(f, t) {
return function (args) {
let previousCall = this.lastCall;
this.lastCall = Date.now();
if (previousCall === undefined // function is being called for the first time
|| (this.lastCall - previousCall) > t) { // throttle time has elapsed
f(args);
}
}
}
As you just proved... There are varying opinions. 😜
To throttle a function means to ensure that the function is called at most once in a specified time period
Not necessarily once. It could be at most X times in a specified time period. So the solution function which throttles a given function should receive 3 params
- the number of times to call (in your case, that is 1)
- the specified period of time
- the callback function itself.
Use RxJs and you'll be happy 😀
Typescript version of throttle function with final and immediate invocations
// Throttle with ensured final and immediate invocations
const throttle = <T extends []> (callback: (..._: T) => void, wait: number): (..._: T) => void => {
let queuedToRun: NodeJS.Timeout | undefined;
let previouslyRun: number;
return function invokeFn(...args: T) {
const now = Date.now();
queuedToRun = clearTimeout(queuedToRun) as undefined;
if (!previouslyRun || (now - previouslyRun >= wait)) {
callback(...args);
previouslyRun = now;
} else {
queuedToRun = setTimeout(invokeFn.bind(null, ...args), wait - (now - previouslyRun));
}
};
};
Thanks to @robertmirro and @FRSgit
Nice one @undergroundwires! But I've skipped leading invocation on purpose, because I was aiming for the simplest implementation. Also, I found out that having this immediate leading method firing is not always a good idea, but that of course depends on a use case.
If we want to write the "fullest" throttle fn I think there should be a possibility to opt out from leading & trailing callback calls. Exactly as they do in lodash.
Here's my version, using TypeScript. It's returning a callback to cancel the timeout, useful if use have to use some cleanup function.
const throttle = <TArgs extends unknown[] = []>(
callback: (...args: TArgs) => void
): ((ms: number, ...args: TArgs) => (() => void)) => {
let timeout: NodeJS.Timeout | undefined;
let lastArgs: TArgs;
const cancel = () => {
clearTimeout(timeout);
};
return (ms, ...args) => {
lastArgs = args;
if (!timeout) {
timeout = setTimeout(() => {
callback(...lastArgs);
timeout = undefined;
}, ms);
}
return cancel;
};
};
Usage:
const cb = (n) => console.log(n);
const throttledCb = throttle(cb);
throttledCb(100, 1);
// wait 50ms
throttledCb(100, 2);
// wait 50ms
// prints 2
Cool and simple.