Settimeout does not work when the window loses focus

I have a simple JavaScript chronograph that displays in a form field called "d2", it is used to check how long someone has been performing 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) } 

The problem is that when a person opens a new tab / uses another program, the timer stops and then resumes when the window focuses again (using Chrome). It has strange behavior, because sometimes it works, sometimes it is not.

I saw a lot of posts that needed a script to stop when out of focus, I want the exact opposite and searched for more than an hour without any luck. Your help is much appreciated!

+6
source share
1 answer

JavaScript timeouts are not guaranteed at specific times. For example, if a thread is busy with something else at the time the timer ends, it will first complete what it does and then execute your timer.

Also, your function does not take into account the time spent inside the display function, so a slight delay will be added for every millisecond.

The correct way to implement a timer is to use system time.

So something like:

 //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 

The Date object can also format this period as a clock for you:

 var m = new Date(milliseconds_since_start) m.getMinutes()+":"+m.getSeconds() 
+3
source

All Articles