JavaScript execute until keypress

前端 未结 2 535
北荒
北荒 2020-12-21 12:47

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?<

相关标签:
2条回答
  • 2020-12-21 13:17

    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
        }
    };
    
    0 讨论(0)
  • 2020-12-21 13:17

    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>
    
    0 讨论(0)
提交回复
热议问题