A short and sweet way to throttle actions being dispatched by your Redux store.
While your effects can throttle and debounce actions they are watching for, it can be helpful to do so earlier on. One reason is to avoid cluttering your Redux devtools with repeats of the same action when debugging:
Here is a class that can be used:
export class ThrottledDispatcher {
private readonly timeLimit: number;
private throttling: boolean = false;
constructor(timeLimitInMilliseconds: number) {
this.timeLimit = timeLimitInMilliseconds;
}
dispatch(store: Store<State>,
action: Action & FunctionIsNotAllowed<Action, 'Functions are not allowed to be dispatched. Did you forget to call the action creator function?'>
): void {
if (!this.throttling) {
this.throttling = true;
store.dispatch(action);
setTimeout(() => {
this.throttling = false;
}, this.timeLimit);
}
}
}
You can use this anywhere, but here is how you would use it in an Angular component class: in your component class, create a property to hold an instance of the class, and give it a default value by instantiating the class, passing in the number of milliseconds you want to use for throttling:
private throttledDispatcher = new ThrottledDispatcher(1000);
Then, anywhere that you are dispatching an action with your
Store
, use the ThrottledDispatcher instead, like this:
// Change this:
this.store.dispatch(
myAction({actionProperty1: "example", actionProperty2: Date.new()})
);
// To this:
this.throttledDispatcher.dispatch(
this.store,
myAction({actionProperty1: "example", actionProperty2: Date.new()})
);
Since this example uses 1000 milliseconds, any time an action is dispatched with this throttler, it will discard all actions passed to it for 1 second, before it is ready to allow another action to be dispatched.
Leave a Reply