JavaScript 执行直到按键

aWe*_*per 4 javascript

我想执行一个循环/动作,直到按下一个键,然后按下我想停止该动作并调用函数getKey。有人可以建议如何做到这一点吗?

function getKey(e) 
{
    var pressedKey;
    if (document.all)   { e = window.event; }
    if (document.layers || e.which) { pressedKey = e.which; }
    pressedCharacter = String.fromCharCode(pressedKey).toLowerCase();
    move(pressedCharacter);

}

document.onkeypress = getKey;
Run Code Online (Sandbox Code Playgroud)

我希望 move() 函数连续执行,直到没有按下某个键。如果它被按下,我想用新的按下字符重新执行 move() 函数

dec*_*eze 5

取决于你如何循环。最简单的方法是使用interval

var interval = window.setInterval(function () {
    // do your thing, do your thing
}, 1000);

document.onkeypress = function () {
    if (/* some specific character was pressed */) {
        window.clearInterval(interval);

        // do some other thing, other thing
    }
};
Run Code Online (Sandbox Code Playgroud)