If the result of the function is useful for you, you can try the extension methods that I wrote for the function interface:
https://gist.github.com/falahati/fda618a9b59bb7d7f33b9ba0d5ef01a3
Usage is as simple as creating a debounce or throttled version of your function by using the trailingDebounce(wait: number)
, leadingDebounce(wait: number)
, trailingThrottle(wait: number)
or the leadingThrottle(wait: number)
function. Here is an example:
class RelativeOffsetCalculator {
public addOffsetTrailingDebounce = this.addOffset.trailingDebounce(500);
public addOffsetLeadingDebounce = this.addOffset.leadingDebounce(500);
public addOffsetTrailingThrottle = this.addOffset.trailingThrottle(500);
public addOffsetLeadingThrottle = this.addOffset.leadingThrottle(500);
private _offset: number;
constructor(offset: number) {
this._offset = offset;
}
public addOffset(base: number): number {
return base + this._offset;
}
}
const instance = new RelativeOffsetCalculator(1);
let executions = 0;
// Call each 100ms for 10 times at a total of a second, should get limited
const intervalTimer = window.setInterval(
() => {
if (executions >= 10) {
window.clearInterval(intervalTimer);
return;
}
instance.addOffsetLeadingDebounce(executions).then(
(result) => console.log(result),
(error) => console.warn(error),
);
executions++;
},
100,
);
// A later call at 2 seconds mark, should not get limited
window.setTimeout(
() => {
instance.addOffsetLeadingDebounce(100).then(
(result) => console.log("Late Execution: ", result),
(error) => console.warn("Late Execution: ", error),
);
},
(10 * 100) + 1000,
);
This results in:
1 1 1 1 1 1 1 1 1 1 Late Execution: 101
,
If the addOffsetTrailingDebounce
function is used, the results are:
10 10 10 10 10 10 10 10 10 10 Late Execution: 101
and if the addOffsetLeadingThrottle
function is used, the results are:
1 1 1 1 1 5 5 5 5 5 Late Execution: 101
and if the addOffsetTraillingThrottle
function is used, the results are:
5 5 5 5 5 10 10 10 10 10 Late Execution: 101
}, 1000); debounced();`
– shrys Nov 29 '19 at 12:13