Remove keydown delay in JavaScript?

前端 未结 3 964
花落未央
花落未央 2020-12-18 06:12

Well, when you hold a key on your keyboard, after the first fire there is a 1sec delay.
You can go ahead and open notepad and hold a key (e.x \'x\') you\'ll see after

3条回答
  •  佛祖请我去吃肉
    2020-12-18 06:42

    You're lucky, I just code this for a game.

    Controller = {
        keyIsDown: [],
    
        // Add a new control. up is optional.
        // It avoids key repetitions
        add: function (key, down, up) {
            $(document).keydown(function(e) {
                if(e.keyCode === key && !Controller.keyIsDown[key]) {
                        down()
                    Controller.keyIsDown[key] = true
                    return false
                }
            })
    
            $(document).keyup(function(e) {
                if(e.keyCode === key) {
                    if(up) up()
                    Controller.keyIsDown[key] = false
                    return false
                }
            })
        },
    }
    

    Example:

    Controller.add(65,
        function () {
            console.log("A is down")
        },
        // This argument is optional
        function () {
            console.log("A is up")
    })
    

提交回复
热议问题