Skip to content

Instantly share code, notes, and snippets.

@wkronemeijer
Last active December 26, 2015 00:09
Show Gist options
  • Save wkronemeijer/7062126 to your computer and use it in GitHub Desktop.
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`.
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