最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Limit how many times an event listener can trigger every second - Stack Overflow

programmeradmin2浏览0评论

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
Add a comment  | 

3 Answers 3

Reset to default 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/

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.

发布评论

评论列表(0)

  1. 暂无评论