Skip to content

Instantly share code, notes, and snippets.

@robertknight
Created July 29, 2019 11:32
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 robertknight/2aae97716f51cad3723f1b41fea7deb7 to your computer and use it in GitHub Desktop.
Save robertknight/2aae97716f51cad3723f1b41fea7deb7 to your computer and use it in GitHub Desktop.
Add a short delay to action dispatches
diff --git a/src/sidebar/store/index.js b/src/sidebar/store/index.js
index 8051a738..1e725db5 100644
--- a/src/sidebar/store/index.js
+++ b/src/sidebar/store/index.js
@@ -71,6 +71,33 @@ function angularDigestMiddleware($rootScope) {
};
}
+/**
+ * Middleware which adds an artificial delay to all actions going through
+ * the store. This is a debugging aid which makes it easier to observe
+ * short-lived states.
+ *
+ * @param {number} delay - Delay in milliseconds.
+ */
+function delayMiddleware(delay) {
+ const queue = [];
+ return next => {
+ function dispatchNextAction() {
+ const action = queue.shift();
+ next(action);
+ if (queue.length > 0) {
+ setTimeout(dispatchNextAction, delay);
+ }
+ }
+
+ return action => {
+ queue.push(action);
+ if (queue.length === 1) {
+ setTimeout(dispatchNextAction, delay);
+ }
+ };
+ };
+}
+
/**
* Factory which creates the sidebar app's state store.
*
@@ -82,6 +109,7 @@ function angularDigestMiddleware($rootScope) {
// @ngInject
function store($rootScope, settings) {
const middleware = [
+ delayMiddleware.bind(null, 300 /* delay */),
debugMiddleware,
angularDigestMiddleware.bind(null, $rootScope),
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment