Last active
December 26, 2015 00:09
-
-
Save wkronemeijer/7062126 to your computer and use it in GitHub Desktop.
Key timer function for reliable input, for use in games and similiar. Originally not mine, but this version uses `addEventListener`.
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
function KeyboardController(keys, repeat) { | |
var timers = {}; | |
document.addEventListener('keydown', function(event) { | |
var key = event.keyCode; | |
if (!(key in keys)) | |
return true; | |
if (!(key in timers)) { | |
timers[key] = null; | |
keys[key](event); | |
if (repeat!==0) { | |
timers[key] = setInterval(keys[key], repeat); | |
} | |
} | |
return false; | |
}, false); | |
document.addEventListener('keyup', function(event) { | |
var key = event.keyCode; | |
if (key in timers) { | |
if (timers[key]!==null) | |
clearInterval(timers[key]); | |
delete timers[key]; | |
} | |
}, false); | |
window.addEventListener('blur', function() { | |
for (key in timers) | |
if (timers[key]!==null) | |
clearInterval(timers[key]); | |
timers= {}; | |
}, false); | |
}; //from stackoverflow: http://stackoverflow.com/a/3691661/1749791 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment