I'm trying to figure out the way I can set up a rolling window for a variable. The variable will record a number increasing # amount of times from the minute before.
My basic interval timer
var kp123 = Number('1');
var myInt = setInterval(function () {
kp123 = 1;
}, 60000);
Whenever a specific command is sent, kp123
gets increased by 1: kp123++;
This variable may increase 20 times every second, or only 2-3 times every second.
Right now how the system is set up, it records the variable # every minute, however, the data gets reset when the interval timer reaches one minute.
var kp123 = Number('1');
var kp123History = []; // The history of kp123 is stored in this variable each minute
var myInt = setInterval(function () {
kp123History.push(kp123);
kp123 = 1;
console.log(kp123History); // You can see the results in the console each minute like this
}, 60000);
or if you only want the previous value, and not the full history, try this
var kp123 = Number('1');
var prevKp123 = null; // The previous value of kp123 is stored in this variable each minute
var myInt = setInterval(function () {
prevKp123 = kp123;
kp123 = 1;
}, 60000);
It sounds like (per the comments) you want a rolling average ( wiki ). You don't really show enough of your code for me to give a specific answer to you, but in general, you can't deduce a rolling average from just averages, you'll need to know actual values and their timestamps. Ie you can't summarize your data and throw away the timestmaps.
class RollingAverage { constructor(windowMs = 1000) { this.windowMs_ = windowMs; this.values_ = []; } addValue(value = 1) { let time = Date.now(); this.values_.push({value, time}); } get average() { let now = Date.now(); this.values_ = this.values_.filter(({time}) => now - time <= this.windowMs_ * 1000); return this.values_ .map(({value}) => value) .reduce((a, b) => a + b) / this.values_.length; } } let test = async () => { let sleep = ms => new Promise(r => setTimeout(r, ms)); let avg = new RollingAverage(); avg.addValue(1); console.log(avg.average); // 1 await sleep(600); console.log(avg.average); // 1 avg.addValue(3); console.log(avg.average); // 2 await sleep(600); console.log(avg.average); // 3 avg.addValue(5); console.log(avg.average); // 4 } test();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.