Skip to content

Instantly share code, notes, and snippets.

@BuonOmo
Last active April 8, 2024 11:51
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 BuonOmo/ca996fb85b3fbd453720fcfb0d9f023d to your computer and use it in GitHub Desktop.
Save BuonOmo/ca996fb85b3fbd453720fcfb0d9f023d to your computer and use it in GitHub Desktop.
Keybinding for a sequence in your browser
// ```
// 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