Created
March 21, 2017 08:38
-
-
Save nicoespeon/1b7a149a5619236b86c429f2e110c251 to your computer and use it in GitHub Desktop.
Blog - Using Observables to make our app work with barcode scanners
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
const ENTER_KEY_CODE = 13 | |
const MAX_INTERVAL_BETWEEN_EVENTS_IN_MS = 50 | |
let keyCodesBuffer = [] | |
let cleanBufferTimeout | |
document.addEventListener("keypress", (event) => { | |
const keyCode = event.keyCode | |
stopCleanBufferTimeout() | |
if(keyCode === ENTER_KEY_CODE) { | |
fillInputWithKeyCodesBuffer() | |
cleanBuffer() | |
} else { | |
addToBuffer(keyCode) | |
cleanBufferAfter(MAX_INTERVAL_BETWEEN_EVENTS_IN_MS) | |
} | |
}) | |
function fillInputWithKeyCodesBuffer() { | |
// … | |
} | |
function cleanBuffer() { | |
keyCodesBuffer = [] | |
} | |
function addToBuffer(keyCode) { | |
keyCodesBuffer.push(keyCode) | |
} | |
function cleanBufferAfter(timeout) { | |
cleanBufferTimeout = setTimeout(cleanBuffer, timeout) | |
} | |
function stopCleanBufferTimeout() { | |
clearTimeout(cleanBufferTimeout) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment