Skip to content

Instantly share code, notes, and snippets.

@mrjacobbloom
Created July 31, 2025 16:36
Show Gist options
  • Select an option

  • Save mrjacobbloom/aae4c5f74516d424b7c1293dd27406d7 to your computer and use it in GitHub Desktop.

Select an option

Save mrjacobbloom/aae4c5f74516d424b7c1293dd27406d7 to your computer and use it in GitHub Desktop.
/**
* A wrapper for async (probably mostly click) event handlers that disables the event target
* until the handler resolves (or rejects). This prevents double-clicks/multiple submissions.
* It sets target.disabled, but it could just as easily modify classNames or style.pointerEvents.
*
* @template {Event} E
* @template Res
* @param {(e: E) => Promise<Res>} callback - Async event handler to wrap
* @returns {(e: E) => Promise<Res>} Wrapped event handler that automagically disables target
*
* @example button.addEventListener('click', disableTargetUntilResolved(async () => { await wait(0.5); }));
*/
export function disableTargetUntilResolved(callback) {
return async e => {
e.target.disabled = true;
try {
const returnVal = await callback(e);
e.target.disabled = false;
return returnVal;
} catch (err) {
e.target.disabled = false;
throw err;
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment