JavaScript执行直到按下键 [英] JavaScript execute until keypress

查看:101
本文介绍了JavaScript执行直到按下键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行一个循环/动作,直到按下一个键并且onpress我想停止该动作并调用函数 getKey 。有人可以建议怎么做吗?

I want to execute a loop/action until a key is pressed and onpress I want to stop that action and call the function getKey. Can anybody suggest how to do this?

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()函数

I want the move() function to be executing continuously till a key is not pressed . if it's pressed i want to re-execute the move() function with the new pressed character

推荐答案

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

Depends on how you loop. The easiest way is with an 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执行直到按下键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆