Created
July 31, 2025 16:36
-
-
Save mrjacobbloom/aae4c5f74516d424b7c1293dd27406d7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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