Perfect solution to solve the browser browser switch background, JS countdown does not execute the problem!
If you do a timer on a web page, the simplest way is to load the web page when the server gives a base time, and then the web side with JS seconds a second to add time, and display. This is usually fine on a PC, but it’s a big problem on a phone, because when the mobile browser is cut to the background, JS will not continue to time, and after a while, when it is cut back to the browser, the timing will only continue from when it was cut out. The time cut out in the middle is unmeasurable.
My solution here is to record the current mobile browser time as soon as you enter the H5 page, and remember the browser’s current nowTime. Then start the countdown with setTimeout or setInterval. When counting down, first take the time of the current browser (again, nextTime of the current browser) and subtract nowTime from the obtained nextTime, we get diffTime. Decrement diffTime with the CountDown seconds returned by the browser, we get a value CountDown, and finally CountDown with CountDown.
The realization idea is: record the time when the user enters the page, and obtain the time of the current browser every second. The diffTime value is the time that the user stays on the page. Finally, we subtract diffTime from the number of seconds returned by the server, and the final value CountDown is our actual CountDown. Because nextTime is fetched every second, there is no need to consider the problem of not executing JS in the background.