Search code examples
javascriptaccelerometeraddeventlistener

JavaScript addEventListener delay


I'm building a mobile application using JavaScript. Into it i need to obtain data from phones' accelerometer, so I attach an event listener to it:

if (window.DeviceOrientationEvent) {
    window.addEventListener("deviceorientation", function (event) {
        if (typeof(event.alpha) != 'undefined') {
            //here goes function for an event
        }
    }, false);
}

But the problem is that it obtains data every millisecond, thus when i call the function to draw and redraw something according to this data, it keeps doing it each millisecond -> application crashes.

Is there any way to delay, or to receive this data in a smaller portions? Is there a function to listen to an event, for example, each half a second?


Solution

  • It's called "function debouncing". Basically, you execute your stuff only once in a certain amount of time. A simple implementation would be:

    var lastExecution;
    addEventListener("deviceorientation", function (event) {
        var now = Date.now();
        if (now - lastExecution < 17) return; // ~60Hz
        lastExecution = now;
        ...
    }, false);
    

    (Yes, lastExecution is undefined at first. It's fine.)