最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript execute until keypress - Stack Overflow

programmeradmin1浏览0评论

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;

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

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;

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

Share Improve this question edited Jan 20, 2011 at 4:48 aWebDeveloper asked Jan 20, 2011 at 4:40 aWebDeveloperaWebDeveloper 38.4k41 gold badges177 silver badges247 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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
    }
};

Use http://www.asquare/javascript/tests/KeyCode.html to find keycodes

<script>
document.onkeyup = getKey;       

function getKey() {
    // If the users hits 'a', stop loopcode from running.
    if(event.keyCode == 65){
        window.clearInterval(interval);
    };
}

var interval = setInterval(function() {
    // loopcode here
}, 1000);

</script>
发布评论

评论列表(0)

  1. 暂无评论