Created
September 20, 2018 02:49
-
-
Save Sawtaytoes/4b0c8aa42ef936eb49ac87aa1c3dc34a to your computer and use it in GitHub Desktop.
Rewriting Flic's button press listener to reduce the timeout between presses
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
import { | |
BUTTON_DOWN, | |
BUTTON_UP, | |
doublePressAction, | |
holdPressAction, | |
singlePressAction, | |
} from './actions' | |
const timeLimit = 300 | |
let startTime = Date.now() | |
let timeoutId = 0 | |
const isWithinTimeLimit = () => Date.now() - startTime < timeLimit | |
const handleButtonPress = buttonState => { | |
if (buttonState === BUTTON_DOWN) { | |
if (isWithinTimeLimit()) { | |
clearTimeout(timeoutId) | |
startTime = 0 | |
doublePressAction() | |
} | |
else { | |
startTime = Date.now() | |
timeoutId = ( | |
setTimeout(holdPressAction, timeLimit) | |
) | |
} | |
} | |
else if (buttonState === BUTTON_UP) { | |
if (isWithinTimeLimit()) { | |
clearTimeout(timeoutId) | |
startTime = Date.now() | |
timeoutId = ( | |
setTimeout(singlePressAction, timeLimit) | |
) | |
} | |
} | |
} | |
const listenForButtonPress = bluetoothAddress => { | |
new FlicConnectionChannel(bluetoothAddress) | |
.on('buttonUpOrDown', handleButtonPress) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment