JavaScript 执行直到按键

标签 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;

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

最佳答案

取决于你如何循环。最简单的方法是使用 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
    }
};

关于JavaScript 执行直到按键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4743500/

相关文章:

javascript - super 简单的javascript函数调用

javascript - 如何开始使用 React 进行函数式编程?

javascript - 使用 php 运行在提交 from 后编辑 css 的 JavaScript?

javascript - 谷歌地图是否将 map 坐标定位到百度 map 中的同一位置?

javascript - 根据年份获取元素总和

javascript - 在 javascript 确认框中包含 php 脚本

javascript - 将 &lt;script&gt; 中的字符串插入到 <a href ="">

javascript - 在 iOS/iphone/ipad 中放大时 jqueryui 对话框的位置问题

javascript - 打印图表时避免出现工具提示

javascript - 使用 create-react-app react ,不同的 env 文件