JSFiddle - React, Tailwind, and code Playground

by mgrcic

HTML

Answer by Rob at <a href="http://stackoverflow.com">Stack Overflow</a>, to <br />&quot;<a href="http://stackoverflow.com/questions/7614340/listen-to-multiple-keydowns/7614586#7614586">Listen to multiple keydowns</a>&quot;.<br /><br />

Hit any arrow key. Current delay: <span id="ms">200</span>ms.<br />
Current direction: <div id="status">N/A</div>

CSS

a, a:visited, a:link, a:active {
    color: green;
    font-weight: bold;
    text-decoration: none;
}
a:hover {
    text-decoration: underline;
}

JavaScript

//As you might see, I've removed the anonymous function wrapper in this example
    /* Change the next variable if necessary */
    var timeout = 200; /* Timeout in milliseconds*/

    var lastKeyCode = -1;
    var timer = null;
    function keyCheck(ev){
        var keyCode = typeof ev.which != "undefined" ? ev.which : event.keyCode;
        /* An alternative way to check keyCodes:
         * if(keyCode >= 37 && keyCode <= 40) ..*/
         /*37=Left  38=Up  39=Right  40=Down */
        if([37, 38, 39, 40].indexOf(keyCode) != -1){

            /* lastKeyCode == -1 = no saved key
               Difference betwene keyCodes == opposite keys = no possible combi*/
            if(lastKeyCode == -1 || Math.abs(lastKeyCode - keyCode) == 2){
                refresh();
                lastKeyCode = keyCode;
            } else if(lastKeyCode == keyCode){
                clear([lastKeyCode]);
            } else {
                /* lastKeyCode != -1 && keyCode != lastKeyCode
                   and no opposite key = possible combi*/
                clear([lastKeyCode, keyCode]);
                lastKeyCode = -1
            }
            ev.preventDefault(); //Stop default behaviour
            ev.stopPropagation(); //Other event listeners won't get the event
        }

        /* Functions used above, grouped together for code readability */
        function reset(){
            keyCombi([lastKeyCode]);
            lastKeyCode = -1;
        }
        function clear(array_keys){
            clearTimeout(timer);
            keyCombi(array_keys);
        }
        function refresh(){
            clearTimeout(timer);
            timer = setTimeout(reset, timeout);
        }
    }

    var lastX = false;
    var lastY = false;
    function keyCombi(/*Array*/ keys){
        /* Are the following keyCodes in array "keys"?*/
        var left = keys.indexOf(37) != -1;
        var up = keys.indexOf(38) != -1;
        var right = keys.indexOf(39) != -1;
        var down =...