When the page loses focus (including minimizing the page and switching to another page without touching the current page), the page is in a static state. This is due to the browser’s rendering mechanism, except for the setInterval timer. When the page loses focus, setInterval will continue to execute according to the established procedure, but DOM is in a static state.

The problem is that when the page regaining focus, the setInterval program will render the DOM all at once, which will cause the setInterval and DOM out of sync. Therefore, it is necessary to clear the timer when the page loses focus.

  • How do I get focus on a page?

Can give the document registered visibilitychange focus events eg (for example) : document. The addEventListener (‘ visibilitychange, fn), it means: The fn function is executed when the page loses focus, and we can clear setInterval in fn. The visiBilityChange event has three states, prerender, Visible, and hidden. To view the states, you can use document.visibilityStage.

Eg:

document.addEventlistener('visibilitychange'.function(){
    if(document.visibilityStage == 'hidden'){
      concle.log('Clear timer, lose focus')})if(document.visibilityStage == 'hidden'){
    concle.log('Get focus')}})Copy the code

You can also use hidden, which has two values true and false

Eg:

document.addEventlistener('vusibilitychange'.function(){
   if(document.hideen){
    concle.log('hideen value is true, indicating departure ')}else{
  concle.log('Hideen value false to get focus')})Copy the code

The setInterval timer is used when the page is cleared after it leaves, and is re-executed when it gets focus. The most important thing is to keep the page setInterval synchronized with DOM