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?
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?
Share Improve this question asked Feb 2, 2013 at 22:04 user2036108user2036108 1,3073 gold badges10 silver badges12 bronze badges 1- 1 What you are looking for is called throttling. Have a look at this question: stackoverflow.com/questions/5031501/…. – Felix Kling Commented Feb 2, 2013 at 22:20
3 Answers
Reset to default 17You 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/
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
}
}
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.