3

Hi I am using a Java Script timer, it works well in IE but in Chrome when the window is minimized it becomes too slow, in Mozilla it stops it timer. Can anyone suggest anything ? My code is as follows :-

<html>
<head>
<script>

var millisec = 0;
var seconds = 0;
var timer;

function display(){

  if (millisec>=9){
     millisec=0
     seconds+=1
  }
  else
     millisec+=1
     document.d.d2.value = seconds + "." + millisec;
     timer = setTimeout("display()",100);
  }

function starttimer() {

  if (timer > 0) {
    return;
  }
  display();    
}
function stoptimer() {
  clearTimeout(timer);
  timer = 0;
}

function startstoptimer() {
  if (timer > 0) {
     clearTimeout(timer);
     timer = 0;
  } else {
     display();
  }
}

function resettimer() {
    stoptimer();
    millisec = 0;
    seconds = 0;
}



</script>
</head>
<body>
<h5>Millisecond Javascript Timer</h5>
<form name="d">
<input type="text" size="8" name="d2">
<input type="button" value="Start/Stop" onclick="startstoptimer()">
<input type="reset" onclick="resettimer()">
</form>

</body></html>
  • See [How can I make setInterval also work when a tab is inactive in Chrome?](http://stackoverflow.com/q/5927284/218196). Not sure about Firefox. – Felix Kling Sep 10 '14 at 16:17
  • It's useful to realize that `setTimeout("display()",100)` is better written as `setTimeout(display,100)` (no brackets!). JavaScript will evaluate `"display()"` which is an inefficiency you don't need. – Halcyon Sep 10 '14 at 16:23

1 Answers1

0

You can not use setTimeout to make a reliable time keeping script.

John Resig explains how JavaScript timers work: http://ejohn.org/blog/how-javascript-timers-work/

The short version is that there is always have a small delay. The millisecond parameter you pass to setTimeout is a "best effort".


If you want to show a live timer consider polling the time really often. If the event loop slows down, there is no effect on your ability to track time, you just get less updates.

http://jsfiddle.net/64pcr7pw/

<script type="text/javascript">
var timer, time = 0, start_time = 0;
function startstoptimer() {
    if (timer) {
        time += new Date().getTime() - start_time;
        start_time = 0;
        clearInterval(timer);
        timer = null;
    } else {
        start_time = new Date().getTime();
        timer = setInterval(function () {
            document.d.d2.value = time + new Date().getTime() - start_time;
        }, 10);
    }
}
function resettimer() {
    time = 0;
    start_time = new Date().getTime();
    document.d.d2.value = "0";
}
</script>

<form name="d">
    <input type="text" size="8" name="d2"/>
    <input type="button" value="Start/Stop" onclick="startstoptimer()"/>
    <input type="reset" onclick="resettimer()" />
</form>
Halcyon
  • 57,230
  • 10
  • 89
  • 128
  • I am trying to call logout() when the timer value is 9000 milliseconds, it executes for the first time, but thereafter it does not logout. – Siddharth Pujara Sep 17 '14 at 13:14