On-site review

Every time a barrage is started, a timer is generated by setInterval. A new barrage is generated every 2 seconds, and the cycle continues. When the page needs to be switched and closed, use clearInterval to clear the timer and clear the generated bullet screen. The brief code is as follows:

letbarrageTimer = null; // Cycle to generate a barrage, one for each callfunction barrageStart() {
  barrageTimer = setInterval(()=>{ createBarrage(); }, 2000); } // Close the barrage and clean up the generated barragefunction barrageEnd() { clearInterval(barrageTimer); barrageList = []; } // The applet page is called each time it loadsonShow() { barrageStart(); } // called when applet page hides or switches backgroundonHide() {
  barrageEnd();
}

Copy the code

When I finished writing this code, confident, feel that it will run no problem, the result…… The barrage timer in the page is still running happily, not being affected by clearInterval…… It’s irritating, but keep smiling…

The problem summary

After querying THE MDN, it is clear that setInterval will actually return the ID of a timer after it is executed. Each generated timer will return its ID, which means that a timer is generated every time a page is entered. When the page is switched quickly, It is possible that the barrageTimer is overwritten by the new timer ID before clearInterval clears the timers generated on the page. As a result, some timers are always running. To solve this problem, check whether the old timer ID exists before generating a new one and stop it again to prevent the timer ids from overwriting each other.

function barrageStart() {
  if (barrageTimer) {
    clearInterval(barrageTimer);
  }
  barrageTimer = setInterval(()=>{ createBarrage(); }, 2000); }function barrageEnd() {
  clearInterval(barrageTimer);
  barrageTimer = 0;
  barrageList = [];  
}
Copy the code

Of course, this is not enough, it is best to use an array to store the timer ID directly, when the need to clean up the unified cleaning

let barrageTimer = null;
let barrageTimerList = []
function barrageStart() {
  barrageTimer = setInterval(()=>{ createBarrage(); }, 2000); barrageTimerList.push(barrageTimer) }function barrageEnd() {
  barrageTimerList.forEach((item,index)=>{
    clearInterval(item)
  })
  barrageTimerList = []
  barrageTimer = 0;
  barrageList = [];  
}
Copy the code