Question

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?

Was it helpful?

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.)

OTHER TIPS

I think you are looking for something like detrottle/debounce

If you have jQuery, these guys made it easy:

window.addEventListener("deviceorientation", function (event) {
    $.throttle( 250, function (event){
        // Code here will excecute every 250 ms
    })
 );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top