javascript 如何修复javascript keydown中的延迟
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12273451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to fix delay in javascript keydown
提问by user1441816
Possible Duplicate:
JavaScript move delay and multiple keystrokes
可能的重复:
JavaScript 移动延迟和多次击键
I'm new and learning HTML5 canvas together with javascript. I've created an event to move an object left and right, and my problem is the delay whenever you hold the key or switch to another key. I know there's missing on my code below please help me. Thank you in advance.
我是新手,正在学习 HTML5 画布和 javascript。我创建了一个事件来左右移动一个对象,我的问题是当你按住键或切换到另一个键时会出现延迟。我知道我的代码下面缺少请帮助我。先感谢您。
c.addEventListener('keydown',this.check,true);
function check(el) {
var code = el.keyCode || el.which;
if (code == 37 || code == 65){
x -=1;
}
if (code == 39 || code == 68){
x += 1;
}
el.preventDefault();
}
回答by nnnnnn
Rather than trying to react directly to the keydown event, I'd suggest you use the keydown and keyup events to maintain a list of which keys are presently down. Then implement a "game loop" that checks every x milliseconds which keys are down and update the display accordingly.
我建议您不要尝试直接对 keydown 事件做出反应,而是建议您使用 keydown 和 keyup 事件来维护当前关闭的键的列表。然后实现一个“游戏循环”,每 x 毫秒检查一次按下的键并相应地更新显示。
var keyState = {};
window.addEventListener('keydown',function(e){
keyState[e.keyCode || e.which] = true;
},true);
window.addEventListener('keyup',function(e){
keyState[e.keyCode || e.which] = false;
},true);
x = 100;
function gameLoop() {
if (keyState[37] || keyState[65]){
x -= 1;
}
if (keyState[39] || keyState[68]){
x += 1;
}
// redraw/reposition your object here
// also redraw/animate any objects not controlled by the user
setTimeout(gameLoop, 10);
}
gameLoop();
You'll notice that this lets you handle multiple keys at once, e.g., if the user presses the left and up arrows together, and the problem of delay between subsequent keydown events when a key is held down goes away since all you really care about is whether a keyup has occurred.
您会注意到,这让您可以同时处理多个键,例如,如果用户同时按下向左和向上箭头,那么当一个键被按下时后续 keydown 事件之间的延迟问题就消失了,因为您真正关心的是是是否发生了keyup。
I realise you may not be implementing a game, but this "game loop" concept should work for you as shown in this very simple demo: http://jsfiddle.net/nnnnnn/gedk6/
我意识到您可能没有实现游戏,但是这个“游戏循环”概念应该适合您,如这个非常简单的演示所示:http: //jsfiddle.net/nnnnnn/gedk6/