I have a Fitbit app and want to write javascript code where every 100 times addEventListener is called, I want the app to take a break for 10 seconds by using setTimeout functionality. The 10 second break will make sure the Fitbit OS does not crash the app. I have the following so far but after the 100 times of addEventListener, there is no 10 second break; where might be the problem?
var i = 0;
function sendmessage() {
if (Accelerometer) {
const accel = new Accelerometer({ frequency: 1 });
accel.addEventListener("reading", () => {
setTimeout(function () {
console.log( `ts: ${accel.timestamp}, \
x: ${accel.x}, \
y: ${accel.y}, \
z: ${accel.z}` );
i++;
console.log(i);
if (i%100 == 0) {
sendmessage();
}
},10000)
You are adding a new event listener every time you call sendMessage(). That is likely what is causing performance issues.
To do what you suggest regarding taking a break you want to store a reference to the setTimeout and check if it is active
Something like: