Skip to content

Instantly share code, notes, and snippets.

@VitorHP
Last active October 10, 2016 18:59
Show Gist options
  • Save VitorHP/79c44251cc090061f692b9e76f164444 to your computer and use it in GitHub Desktop.
Save VitorHP/79c44251cc090061f692b9e76f164444 to your computer and use it in GitHub Desktop.
function chargeBeam(key, onCharging, onCharged, onCancel, onShoot){
var chargingTimer;
var cleared = true;
function cancelCharge(){
if (!cleared) {
clearTimeout(chargingTimer);
cleared = true;
onCancel && onCancel();
}
}
function shootChargeBean() {
document.removeEventListener('keyup', shootChargeBean)
onShoot && onShoot();
cleared = true;
}
document.addEventListener('keydown', function(e) {
if (e.keyCode === key && cleared) {
clearTimeout(chargingTimer);
chargingTimer = setTimeout(function(){
onCharged && onCharged();
document.removeEventListener('keyup', cancelCharge)
document.addEventListener('keyup', shootChargeBean)
}, 2000)
onCharging && onCharging();
cleared = false;
document.addEventListener('keyup', cancelCharge)
}
})
}
chargeBeam(65,
function onCharging(){ console.log("Charging..") },
function onCharged(){ console.log("Charged!") },
function onCancel(){ console.log("Charge Canceled") },
function onShoot(){ console.log("WOOOOOOOOOOSH") }
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment