In JavaScript, setInterval will speed things up when we switch browsers

Original link:Perfect fix for setInterval acceleration on browser switches

The reasons for this are:

It is found that this is because the browser is in line with the nature of memory saving, when switching to another page, the oil production system page timer does not move, but the animation is still arranged, when switching back, the animation is accelerated, there is an error, such as in the wheel map and other pages often happen

Here are three things we need to know:

  • Document. Onvisibilitychange:

This event is triggered whenever a page changes, either by switching to another page or by shrinking the browser.

  • document.hidden

This means true if the page is not the current page, false otherwise

  • document.visibilityState:

This property has four values, including Visible, Hidden, prerender, and unloaded

Visible indicates that the current web page is visible or partially visible.

Hidden: The current web page is not visible

Prerender Web page content is pre-rendered and invisible to the user

This value is returned if the document is unloaded

The actual operation effect is as follows:

document.onvisibilitychange=function(){
	console.log("hidden"+":"+document.hidden);
	console.log("visibilityState"+":"+document.visibilityState);
}
Copy the code

The execution effect is as follows:

Fix setInterval in browser switch:

If the page is invisible, we clear the timer. If the page is visible, we restart the timer.

. So we need to use the document onvisibilitychange for listening, then use the document. The visibilityState or is the document. The hidden.

Actual operation:

document.onvisibilitychange=function(){ if(document.visibilityState=="visible"){ timer=setInterval(slidemove, 1000); }else{ clearInterval(timer); }}Copy the code

Jq animate solution

If you use jQ animate, you simply add stop(true,true) to the end of the animate method.

$(".slidePanel").stop(true,true).animate({
	"left": -iNow*varWidth+"px",
	"speed":300
});
Copy the code