aWebDeveloper
aWebDeveloper

Reputation: 38352

JavaScript execute until keypress

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

Upvotes: 4

Views: 7057

Answers (2)

Jeff Lamb
Jeff Lamb

Reputation: 5865

Use http://www.asquare.net/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>

Upvotes: 2

deceze
deceze

Reputation: 522024

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

Upvotes: 5

Related Questions