Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 356
Kakofonn Avatar asked Jul 22 '26 21:07

Kakofonn


1 Answers

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

like image 117
MaxArt Avatar answered Jul 25 '26 10:07

MaxArt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!