Search code examples
javascriptsettimeoutonkeypress

onkeydown event to only execute at 10th of a second


So I have a little square moving around a grid, but when I execute the onkeydown event my square moves very fast. I only want it to execute once every 10th of a second so that my little square doesn't run into a pair of scissors. But when I try a setTimeout function it only times out for the very first keydown, and then continues to executes fast and when you release the key it's still executing to catch up. This is very unsafe for my little square. Any help would be much appreciated.

Here is the code without the setTimeout function, only because I feel it's not the right way to go:

function checkArrowKeys(e){
    var arrs= [], key= window.event? event.keyCode: e.keyCode;
    arrs[37]= 'left';
    arrs[38]= 'up';
    arrs[39]= 'right';
    arrs[40]= 'down';
    if(arrs[key]){
        transition(arrs[key]);
    }
}
document.onkeydown=checkArrowKeys;

Solution

  • You could stop the execution of your transition by exiting the function if your preset delay hasn't occurred.

    var bWait=false;
    function checkArrowKeys(e){
        if (bWait) return;
        var arrs= [], key= window.event? event.keyCode: e.keyCode;
        arrs[37]= 'left';
        arrs[38]= 'up';
        arrs[39]= 'right';
        arrs[40]= 'down';
        if(arrs[key]){
            transition(arrs[key]);
        }
        bWait=true; //wait for 10 milliseconds
        window.setTimeout("bWait=false;",10);
    }
    document.onkeydown=checkArrowKeys;
    

    What do you think?