简体   繁体   中英

Settimeout not working when window loses focus

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) 
}

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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM