Last active
April 8, 2024 11:51
-
-
Save BuonOmo/ca996fb85b3fbd453720fcfb0d9f023d to your computer and use it in GitHub Desktop.
Keybinding for a sequence in your browser
This file contains 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
// ``` | |
// sequenceKeyBinding('hello', () => { console.log('world') }) | |
// ``` | |
const sequenceKeyBinding = (seq, action, timeoutMs=3000) => { | |
let curr = 0 | |
let timeout = null | |
document.body.addEventListener('keydown', (e) => { | |
if (seq[curr] == e.key) { | |
if (!timeout) { | |
timeout = setTimeout(() => { | |
curr = 0 | |
timeout = null | |
}, timeoutMs) | |
} | |
if (++curr === seq.length) { | |
clearTimeout(timeout) | |
timeout = null | |
action() | |
} | |
} else if (timeout) { | |
clearTimeout(timeout) | |
timeout = null | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment