10

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?

user2036108
  • 1,227
  • 1
  • 10
  • 12
  • 1
    What you are looking for is called *throttling*. Have a look at this question: http://stackoverflow.com/questions/5031501/how-to-rate-limit-ajax-requests/. – Felix Kling Feb 02 '13 at 22:20

3 Answers3

17

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/

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
1

You could do something like this, where you check how often your event is called in a 1 second interval and whether or not you process it. Code sample, rough outline of what I was thinking (no gaurantee (like that spelling)).

function process_event() {
var curr = new Date().getTime();
if ((curr - timeObj.last) < 1000) { //One Second 
     if (timeObj.counter > 25) {
        for (var x=0;x<timeObj.times;x++) {
             if ((curr - timeObj.times[x]) >= 1000) {
                   timeObj.times.splice(x, 1);
                   timeObj.counter -= 1;
             }
        }
     }
     else { 
         timeObj.counter += 1;
         timeObj.times[timeObj.times.length()-1] = curr;
     }
}
else {
    timeObj.counter = 0;
    timeObj.times = [];
}
if (timeObj.counter > 25) {
    return False
 }  
 else {
   return True
 } 
}
Sean McCully
  • 1,122
  • 3
  • 12
  • 21
0

Initialize a variable that increments every time the event listener activates. Make it so that the function the event listener outputs only occurs when the variable is below 25.

David
  • 877
  • 1
  • 7
  • 18