我试图弄清楚为变量设置滚动窗口的方式。 该变量将从前一分钟开始记录增加#个次数的数字。
我的基本间隔计时器
var kp123 = Number('1');
var myInt = setInterval(function () {
kp123 = 1;
}, 60000);
每发送一个特定命令,kp123
就会增加1:
kp123++;
此变量每秒可能增加20次,或者每秒仅增加2-3次。
现在如何设置系统,它每分钟记录一次变量#,但是,当间隔计时器达到一分钟时,数据将重置。
答案 0 :(得分:0)
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);
或者如果您只想使用以前的值而不是完整的历史记录,请尝试
var kp123 = Number('1');
var prevKp123 = []; // The previous value of kp123 is stored in this variable each minute
var myInt = setInterval(function () {
prevKp123 = kp123;
kp123 = 1;
}, 60000);
答案 1 :(得分:0)
听起来(根据评论)您想要滚动平均值(wiki)。您没有真正为我显示足够的代码来为您提供特定的答案,但是总的来说,您不能仅从平均值中得出滚动平均值,您需要知道实际值及其时间戳。即您无法汇总数据并丢弃时间戳记。
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();