Tracking a value for X time

118 Views Asked by At

How would one go about tracking a value over a rolling time period in Nodejs?

IE: An event that may return '1' or '0' every 10 sec's, if this event were to return a '1' every 10's for the last 5 minutes then emit true but if there was one or more instances of a '0' for the last 5 minutes then emit false

i have done some googling, but just seem to keep getting pointed to the setTimer function, which is not what I'm looking for.

could anyone provide some pointers, appreciate any help.

1

There are 1 best solutions below

0
Joseph Balnt On BEST ANSWER

In a rare case of your problem where if there is one or more instance of 0, we can emit false whenever the event gives a 0:

var place = 0;
var intv = setInterval(() => { 
  if (place > 30){ // 30 * 10 seconds = 5 mins
    console.log("true");
    clearInterval(intv);
  }
  place++;
  if (event() == '0'){
    console.log("false");
    clearInterval(intv);
  }
}, 10000); //10 seconds

If it was more than 1 time, for example the problem was 7 or more times, we can use a variable to keep track of the event outcomes:

var instancesOfZero = 0;
var place = 0;
var intv = setInterval(() => {
  if (instancesOfZero == 7) { // 7 is the desired # of instances to emit false
    console.log("false");
    clearInterval(intv);
  }
  if (place > 30){
    console.log("true");
    clearInterval(intv);
  }
  place++;
  if (event() == '0'){
    instancesOfZero++;
  }
}, 10000);