Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在浏览器中更改选项卡时,时钟延迟_Javascript - Fatal编程技术网

Javascript 在浏览器中更改选项卡时,时钟延迟

Javascript 在浏览器中更改选项卡时,时钟延迟,javascript,Javascript,我想显示实时时钟。它工作得很好。但当我换了一段时间的标签,然后用时钟回到标签,它就延迟了 这是我试过的 index.html <!DOCTYPE html> <html> <head> <title>CLOCK</title> </head> <body> <div id="clock"></div> <script type="text/jav

我想显示实时时钟。它工作得很好。但当我换了一段时间的标签,然后用时钟回到标签,它就延迟了

这是我试过的

index.html

<!DOCTYPE html>
<html>
<head>
    <title>CLOCK</title>
</head>
<body>
<div id="clock"></div>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
main.js

let clock_div = document.getElementById('clock');

let current_time = new Date('2020-11-13 08:00:00');

renderTime();

function renderTime() {
    clock_div.innerHTML = 
        ( current_time.getHours() == 0 ? "12" : ( current_time.getHours() < 10 ? "0" + current_time.getHours() : ( current_time.getHours() > 12 ? ( (current_time.getHours() - 12) < 10 ? "0" : "" ) + current_time.getHours() - 12 : current_time.getHours() ) ) ) 
        + ':' + ( current_time.getMinutes() < 10 ? "0" + current_time.getMinutes() : current_time.getMinutes() ) + ' ' 
        + ':' + ( current_time.getSeconds() < 10 ? "0" + current_time.getSeconds() : current_time.getSeconds() ) + ' ' 
        + ( current_time.getHours() >= 12 ? "PM" : "AM" );

    current_time.setMilliseconds( current_time.getMilliseconds() + 1000 );
    setTimeout(renderTime, 1000);

}
让clock_div=document.getElementById('clock');
当前时间=新日期('2020-11-13 08:00:00');
renderTime();
函数renderTime(){
clock_div.innerHTML=
(current_time.getHours()==0?-12):(current_time.getHours()<10?-0“+current_time.getHours():(current_time.getHours()>12)((current_time.getHours()-12)<10?-0:“)+current_time.getHours()-12:current_time.getHours()))
+“:”+(current_time.getMinutes()<10?“0”+current_time.getMinutes():current_time.getMinutes())+”
+“:”+(current_time.getSeconds()<10?“0”+current_time.getSeconds():current_time.getSeconds())+”
+(当前时间.getHours()>=12?“下午”:“上午”);
current_time.setmillizes(current_time.getmillizes()+1000);
setTimeout(renderTime,1000);
}

一旦选项卡位于后台(或最小化浏览器窗口),多个浏览器将暂停任何正在运行的进程”。当页面重新聚焦时,它们将恢复。这里的缺陷是您假设每秒都会调用
renderTime
。。但如果是在后台,你就不能保证。不要添加秒并假设每秒触发一次,而是在
renderTime
中收集
newdate()
。您还可以查看
setInterval
,而不是重复
setTimeout
calls。您不知道为什么添加了该链接@GalaxyCat105@PraveenKumarPurushothamanWeb Workers API(我链接到)允许脚本在后台运行,这是OP想要的。是的@PraveenKumarPurushothaman一些信息会有所帮助。不仅仅是一个链接。对于像我这样没有经验的用户来说,这是令人困惑的。