Mackan90096
Mackan90096

Reputation: 354

How to make gamepad keys fire slower?

I'm currently making a game with html5, css and javascript, it works as it should and all, but when I press a button on my wired xbox360 controller, it fires the callback I've set almost 50 times in less than a second!

How do I make the callback only fire once per second using the Gamepad API in JavaScript?

I've tried using a cooldown timer like so

var pressCool = false;

if(buttonPressed(xbox.stick2)){
    if(!pressCool){
        var e = jQuery.Event("keydown");
        e.keyCode = keys.custom.stick2;
        $(document).trigger(e);
        pressCool = true;
    }
}

setTimeout(function(){
    if(pressCool){
        pressCool = false;
    }
}, 1000);

But this still gives me more than one firing of the callback.

Upvotes: 0

Views: 55

Answers (1)

hindmost
hindmost

Reputation: 7195

Your setTimeout callback actually do nothing. On each call it only checks if pressCool flag is set, but it always equal to false, so this condition is never true.

The code outside setTimeout runs only once. Whereas it seems that it has to be called on each game frame (game loop iteration).

You have to place all code which relevant to game loop iteration into one function and place its call into setTimeout callback.

So your code should look like this:

...
function update() {
    if(pressCool){
        pressCool = false;
    }
    if(buttonPressed(xbox.stick2)){
        if(!pressCool){
            var e = jQuery.Event("keydown");
            e.keyCode = keys.custom.stick2;
            $(document).trigger(e);
            pressCool = true;
        }
    }
    ...
}

setTimeout(function(){
    update();
}, 1000);

Also I recommend you to read the MDN article relevant to your problem.

Upvotes: 0

Related Questions