Skip to content

Instantly share code, notes, and snippets.

@n3dst4
Created May 26, 2021 09:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n3dst4/ae0901601e5c8ce69843d87bb4f75195 to your computer and use it in GitHub Desktop.
Save n3dst4/ae0901601e5c8ce69843d87bb4f75195 to your computer and use it in GitHub Desktop.
redux debounce middleware
import { Dispatch } from "react";
import { AnyAction, Store } from "redux";
import { State } from "./types";
/**
* Create a middleware that will debounce actions of a given kind.
*
* Debouncing means that if a certain action happens more than once in a given
* period, only the last one will actually take effect.
*/
export default (
actionType: string,
delay: number,
) => (
_: Store<State>,
) => {
let timeout: any;
return (next: Dispatch<AnyAction>) => (action: AnyAction) => {
if (action.type === actionType) {
clearTimeout(timeout);
timeout = setTimeout(() => { next(action); }, delay);
} else {
return next(action);
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment