setInterval() is not working properly for inactive tab

4.1k views Asked by At

i am developing one timer which is taking record of time. for that i am using setInterval method of java script now problem is that it's not working properly if tab is inactive.

one solution i got to store old time and subtract from new time with that one problem if after starting the timer if user change system time then it affect on to the my timer. please inform me if there is any other possible way or solution.

timerInterval = setInterval(function() {
    seconds=seconds+1;
    if(seconds==60)
    {
        minutes=minutes+1;
        if(minutes==60)
        {
            minutes=0;
            hours=hours+1;
        }                                               
        $("#task"+aData['taskId']).html(("0" + hours).slice(-2)+":"+("0" + minutes).slice(-2));
        seconds=0;
    }
},1000);
2

There are 2 answers

1
AudioBubble On

Try setTimeout instead of setInterval

setInterval do not prioritize the calling function depending on the browser load. i have gone through same problem and i resolved it using setTimeout

5
Jason van der Zeeuw On

I made a plunker, and I edited my time, but the timer just keeps going.

$(document).ready(function(){
  var seconds = 0;
  var hours = 0;
  var minutes = 0;

  setInterval(function(){
    seconds++;
    if(seconds == 60)
    {
        seconds=0;
        minutes++;
        if(minutes == 60)
        {
            minutes=0;
            hours++;
        }    
    }
    $(".timer").html(("0" + hours).slice(-2)+":"+("0" + minutes).slice(-2)+":"+("0" + seconds).slice(-2));
  },1000);
});

and in the html a tag to show the timer:

<h2 class="timer"></h2>

http://plnkr.co/edit/yWQWrGxnkgOFvXDoLNhU?p=preview

Let me know if this helps you out!