Executing code every 100ms

I have an android app that pulls in sensor (GPS, accelerometer) data. Once the start button is pressed recording starts, and once stop is pressed recording stops

I want to poll from all the sensors every 100ms while its recording, and store it all into a collection with a timestamp

Whats the correct way to execute a piece of code continuously every 100ms? Would you just start an infinite while loop on button press and break when stop is pressed? Or is there a neater way?

I’d hesitate executing polling every 100ms. This could run into trouble really quickly.

Simplistically, I’d look at events triggering the update such as onGpsStatusChanged()

This being an Adroid app, you’d probably find better answers on an Android forum or stackoverflow: http://stackoverflow.com/questions/8146511/android-listen-for-change-in-gps-status

The issue with listening to events is that I can’t ensure the timings will be the same

One requirement is that the timestamp on the gps and accelerometer data being stored is the same. In other words, they need to be polled simultaneously

window.setInterval

I would also look into using a recursive setTimeout in case the workload is heavy that it might fall behind in those 100ms.

1 Like

I find setInterval not to be accurate. Even when you set the interval to 100ms, this won’t trigger exactly at 100ms as other processes get in the way which can cause a delay in the interval execution. Even when fired every second, after a few minutes the seconds begin to lag in comparison to real time. Instead timers based on the Date() referenced as quickly as possible seem to do the trick

I guess you can set the interval to 50ms and have a relatively accurate reading using Date() getMilliseconds() to use as your to-the-100ms timestamp…

2 Likes