问题描述
我有一个简单的JavaScript计时码表,该计时码表显示在名为"d2"的表单字段上,用于检查某人执行特定任务需要多长时间:
I have a simple JavaScript chronograph that displays on a form field called "d2", it is used to check how long someone takes on doing a specific task:
var milisec=0
var seconds=0
var complemento1=""
document.form1.d2.value='00:00:00'
function display(){
if (milisec>=9){
milisec=0
seconds+=1
}
else{
milisec+=1
}
complemento1=complemento2=complemento3="";
if ((seconds%60)<10) complemento1="0";
if ((Math.floor(seconds/60)%60)<10) complemento2="0";
if ((Math.floor(seconds/3600))<10) complemento3="0";
document.form1.d2.value=complemento3+Math.floor(seconds/3600)+":"+complemento2+(Math.floor(seconds/60)%60)+":"+complemento1+(seconds%60)
setTimeout("display()",100)
}
问题在于,当此人打开新标签页/使用其他程序时,计时器会停止运行,然后在窗口再次聚焦时恢复计时(使用Chrome).它具有最怪异的行为,因为有时它起作用,有时却不起作用.
The problem is that when the person opens a new tab / uses another program the timer stops, and then resumes when the window is focused again (Using Chrome). It has the weirdest behavior, because sometimes it works, sometimes it doesn't.
我看到很多帖子都需要脚本在不集中时停止,我希望恰好相反,并搜索了一个多小时而没有运气.非常感谢您的帮助!
I saw many posts that needed a script to stop when not on focus, I want the exact opposite and searched for over an hour with no luck. Your help is greatly appreciated!
推荐答案
不能保证在特定时间执行JavaScript超时.例如,如果在计时器完成时线程正在忙于其他事情,它将首先完成其工作,然后执行您的计时器.
JavaScript timeouts are not guaranteed be executed at a specific time. For example if the thread is busy with something else at the time when the timer finishes, it will first finish what it is doing and then execute your timer.
您的函数也没有考虑到显示函数内部所花费的时间,因此每毫秒将增加一点延迟.
Also your function does not take into account the time spend inside the display function, so a little delay will be added for each millisecond.
实现计时器的正确方法是使用系统时间.
The correct way to implement a timer is using the system time.
所以像这样:
//Call at the beggining to save the start time
var start_time = new Date()
// Compute seconds (does not matter when/how often you call it.)
var milliseconds_since_start = new Date().valueOf() - start_time
Date对象还可以将这段时间格式化为您的时钟:
The Date object can also format this period as a clock for you:
var m = new Date(milliseconds_since_start)
m.getMinutes()+":"+m.getSeconds()
这篇关于当窗口失去焦点时,SetTimeout无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!