Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit how many times an event listener can trigger every second

Tags:

javascript

I'm playing with the Gamepad API - in particular the axes using the joysticks on a controller. The position of these updates a lot and often - as such, the event that I'm listening for (movement on the sticks) also happens a lot. Is there any way to limit it happening to, say, 25 times a second in order to reduce lag?

like image 258
user2036108 Avatar asked Feb 02 '13 22:02

user2036108


1 Answers

You can't limit the rate at which JavaScript events are triggered, but your event handler could opt to do nothing on some calls. Here is an example using mousemove (I don't know which Gamepad API you're talking about):

var lastMove = 0;
document.addEventListener('mousemove', function() {
    // do nothing if last move was less than 40 ms ago
    if(Date.now() - lastMove > 40) {
        // Do stuff
        lastMove = Date.now();
    } 
});

http://jsfiddle.net/jk3Qh/

like image 125
bfavaretto Avatar answered Oct 07 '22 00:10

bfavaretto