Limit how many times an event listener can fire every second

I play with the Gamepad API, in particular, using the joysticks on the controller. The position of these updates is many and often - as such, the event that I listen to (movement on sticks) also happens a lot. Is there a way to limit this to, say, 25 times per second in order to reduce the lag?

+4
source share
3 answers

You cannot limit the speed at which JavaScript events are fired, but your event handler may not do anything on certain calls. Here is an example using mousemove (I don’t know which Gamepad game interface you are 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/

+8
source

You can do something like this, where you check how often your event is fired with an interval of 1 second and whether it processes it. Sample code, rough outline of what I thought (no gaurantee (like this 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 } } 
+1
source

Initialize a variable that increments each time an event listener is activated. Make it so that the function output to the event listener appears only when the variable is below 25.

0
source

All Articles