Background description
Let arr = [{t: time,v: value}] saves nearly two hours of data. Array length is certain, use timer interval 30 seconds to calculate the data, delete the first element of the array, add the latest data to the end of the array.
Problem description
When my browser window is minimized or I switch to another page, the page timer stops. When too much time is switched back again, the timer is activated and the data in my time array will be abnormal.
The solution
Use VisiBilityChange to listen for the visibility of the window and initialize it when the visibility is repaired
mounted() {
// Perform initialization for the first time
this.init();
this.timer = setInterval(() = > {
// Execute on time
this.getData();
}, 3000);
// Use visiBilityChange to listen on whether the window is visible
document.addEventListener("visibilitychange".this.handleVisiable);
},
methods: {
handleVisiable(e) {
// The window is visible
if (e.target.visibilityState === "visible") {
// reinitialize the time
this.init(); }},getData(){
// My business operation data
arr.shift();
arr.push(v);
},
/ / initialization
init(){
let d = new Date(a); d.setHours(d.getHours() -1);
this.startDate = d;
arr = []
}
},
/ / destroy
beforeDestroy() {
clearInterval(this.timer);
this.timer = "";
document.removeEventListener("visibilitychange".this.handleVisiable);
},
Copy the code