Search code examples
javascriptarraysangulartelemetry

Loop through array at certain speed in Javascript


I'm new here so spare me please.

I'm working on a little hobby project of mine where an application gathers telemetry which is recorded and saved at 60Hz (so 60 index in an array for each second). This is always the case.

I then want to 'play through' this array at the regular speed as if you're playing a video. But instead of seeing a video I want to show the current data from each index that you're at on the frontend.

The structure of the array is not made yet, but I assume I will just store and load a JSON file somewhere in the database. This then should be played through in my frontend. I've used Angular (6) to build that, so it would be great if it could be mixed with Angular (to keep track of the progress of which index you are now, and bind the values of the current index to the frontend).

Would it be easy to just use 0-1-2-etc for indexx, or maybe something like timestamps?

Any suggestions are welcome. The most important thing here is to keep it quick so you don't need a strong rig to play this.

Thanks in advance!


Solution

  • You need to use setInterval function in which you will iterate over the array according to your frequency. So if your frequency is 60hz that means you want to iterate to next element in array after every 1000 / 60 milliseconds

    var data = [1, 2, 3, 4, 5]
    
    var currentIndex = 0;
    
    var interval = 1000 / 60
    
    var id = setInterval(function() {
      // do your thing
      if(currentIndex == (data.length-1)) {
        clearInterval(id)
      } else {
        currentIndex++
      }
    }, interval)
    

    This is not a particularly iterating over array but rather doing some action after interval of time and then moving to next item and when you are done with array this will clear the interval. Perhaps linked list will be more helpful than array here