For the sake of energy saving, some browsers will pause timed tasks such as setTimeout when entering the background (or when they lose focus). When the
user returns to the browser, the timed tasks will be reactivated. The timed task is
said to be paused, but it should be said to be delayed. , 1s task is delayed to 2s, 2s is delayed to 5s, the actual situation varies with browsers
Run the code in Chrome
var t = new Date() * 1
function fun1() {
var _t = new Date() * 1
console.log(_t - t)
t = _t
setTimeout(fun1, 1000)
}
fun1()
The console will print a similar result.
Green means the interval between each task execution is about 1000ms during normal operation.
Red means the interval between each execution task is about 2000ms when the browser enters the background.
This is the performance of the browser's energy saving.
Sometimes it is an insignificant function. Whether it is paused or delayed, it
does not matter. But when we don't want it to be paused, how can setTimeout work properly?
Solution
var c3 = document.createElement("audio")
c3.src = "https://www.runoob.com/try/demo_source/horse.mp3"
c3.volume = 0
// 有些浏览器很严格, 需要设一个极小的音量, 或换一个没有声音的音频文件
c3.loop = true;
c3.play();
var t = new Date() * 1
function fun1() {
var _t = new Date() * 1
console.log(_t - t)
t = _t
setTimeout(fun1, 1000)
}
// fun1()
Anyone who has watched videos on the web knows that if you minimize the window or activate other pages, the media file will not stop playing.
The principle of this method is to play the media, so that the browser thinks that the window has not entered the background, and thus does not do setTimeout. Out of suspension
Disadvantages
But this method also has limitations
It only works on the PC side
. This method is not necessarily effective on the mobile side.
To play a media file, there must be user behavior,
that is to say, if the code executes fun1(), it will be invalid, and it must be called with an event such as click
So it is not a last resort, and this method is not recommended
end