Skip to content

Commit

Permalink
add throttle
Browse files Browse the repository at this point in the history
  • Loading branch information
stanislav-atr committed Oct 10, 2022
1 parent a721c37 commit 3c61def
Showing 1 changed file with 25 additions and 1 deletion.
26 changes: 25 additions & 1 deletion src/scriptlets/trusted-click-element.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ export function trustedClickElement(source, selectors, extraMatch = '', delay =
const log = console.log.bind(console);

const OBSERVER_TIMEOUT = 10000;
const THROTTLE_DELAY_MS = 20;
const COOKIE_MATCH_MARKER = 'cookie:';
const LOCAL_STORAGE_MATCH_MARKER = 'localStorage:';
const COMMON_DELIMITER = ',';
Expand Down Expand Up @@ -214,8 +215,31 @@ export function trustedClickElement(source, selectors, extraMatch = '', delay =
}
};

const throttle = (cb, ms) => {
let wait = false;
let savedArgs;
const wrapper = (...args) => {
if (wait) {
savedArgs = args;
return;
}

cb(args);
wait = true;

setTimeout(() => {
wait = false;
if (savedArgs) {
wrapper(savedArgs);
savedArgs = null;
}
}, ms);
};
return wrapper;
};

// eslint-disable-next-line compat/compat
const observer = new MutationObserver(findElements);
const observer = new MutationObserver(throttle(findElements, THROTTLE_DELAY_MS));
observer.observe(document.documentElement, {
attributes: true,
childList: true,
Expand Down

0 comments on commit 3c61def

Please sign in to comment.