0

I have a timer set on my application using html 5 and jquery. Now when I move on to different tab or I minimize my window, the timer for that few seconds stops. And again as I open the window(tab or browser page, whatever u say)the timer starts. But it gets pause for those seconds. What should be the issue ? What code should I write for it ?

Code for getting the timer is:

Here the timer is set and it runs, but as soon as i move my focus to other page, the timer is paused. A function is just shown here.

function showTime()
{
    if(ms>=100){
        ms = 0;
        s++;
    }
    // calculates seconds and hours also

    var temp= $("#clock").text(checkTime(h)+":"+checkTime(m)+":"+checkTime(s)+"."+checkTime(ms));
    timer=setTimeout('showTime()', 10);
}

checktime is a function which just add a zero in front of numbers<10.

Gajotres
  • 57,309
  • 16
  • 102
  • 130
user2387900
  • 215
  • 1
  • 6
  • 13
  • 1) show the code. 2) you cannot rely on the timer to run precisely. If you need it to, get the date when ou need to test elapsed time, rather than rely on setInterval or setTimeout only – mplungjan Jul 18 '13 at 06:22
  • There are many posts on StackOverflow about this. [This][1] for example. [1]: http://stackoverflow.com/questions/12536627/javascript-countdown-timer-that-stops-when-window-is-not-in-focus – Jay Patel Jul 18 '13 at 06:51
  • Why not use a setInterval inestead of a recursive setTimeout? – Irvin Dominin Jul 18 '13 at 06:52
  • when should i use set interval and when set time out ?? – user2387900 Jul 18 '13 at 07:09
  • The difference between using setTimeout and setInterval in your example is that setTimout will execute 10 milliseconds AFTER successfully calling showTime where as setInterval will call it regardless. Please describe exactly what you are trying to achieve? I can tell you immediately you will not succeed in showing a smooth clock with 100s of milliseconds – mplungjan Jul 18 '13 at 07:42
  • @mplungjan,, I want that when I move out of my page, my code should work. But when I move out, i.e focus out, my timer pauses and when I move in, timer starts auto. – user2387900 Jul 18 '13 at 18:21
  • @mplungjan can u pls guide me.. – user2387900 Jul 19 '13 at 15:41
  • Just do a new date each time and see if elapsed tim has changed instead of using a counter – mplungjan Jul 19 '13 at 18:40
  • http://www.sitepoint.com/creating-accurate-timers-in-javascript/ – mplungjan Jul 21 '13 at 17:46

1 Answers1

0

When you want a function to be called in fixed intervals use setInterval

 setInterval(showTime, 10);//calls showTime every 10 miliseconds
raam86
  • 6,785
  • 2
  • 31
  • 46