setTimeout inside addEventListener to have the app take a break every 100 addEventListener events

180 Views Asked by At

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

There are 1 best solutions below

1
On

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:

function sendmessage() {

  let timer = null;

  if (Accelerometer) {

    const accel = new Accelerometer({
      frequency: 1
    });

    accel.addEventListener("reading", () => {
      if (i % 100 == 0 && !timer) {
        // do something with the data here
        
        // then set a timeout
        timer = setTimeout(function() {
         // reset the variable
          timer = null;
        }, 10000)
      }
    })
  }
}