0

I have a working count down timer in java script and it count down from 120 seconds to 0, now I want to change it to becomes a COUNT UP timer, try few thing still not work. could anyone help to change it to COUNT UP instead of COUNT DOWN.

Here is the code below:

<script type="text/javascript" >
var m = 0;
var s = 120;
var timer_container = document.getElementById("survey-timer");
timer_container.innerHTML = s + "." + m;

function timer() {
    if (m<=0) {
        m = 9;
        s -= 1;
    }
    if(s>=0) {
        m -= 1;
        timer_container.innerHTML = s + "." + m;
        setTimeout(timer,100);
    }
}
</script>
OptimizedQuery
  • 1,262
  • 11
  • 21
user1985788
  • 39
  • 3
  • 9

2 Answers2

1

You want to count up from 120 or from 0.. below one just count up from 0..

   <script type="text/javascript" >
    var m=0
    var s=0
    var timer_container=document.getElementById("survey-timer");
    timer_container.innerHTML=s+"."+m;

    function timer(){
    if (m>=9){
        m=-1;
        s+=1;
    }
    if(s>=0){
        m+=1;
        timer_container.innerHTML=s+"."+m;
        setTimeout(timer,100);
    }
    }
    </script> 

Here is working example from jsfiddle

rahul maindargi
  • 5,359
  • 2
  • 16
  • 23
1

If it were me, I would do this:

var base = new Date();
var timer_container = document.getElementById("survey-timer");

timer();

function timer() {
  var now = new Date();
  // elapsed time in seconds
  var elapsed = (now - base) / 1000.0;
  timer_container.innerHTML = elapsed.toFixed(1);
  setTimeout(timer, 100);
}
<div id="survey-timer">&nbsp;</div>

Because I think the technique used in the question and in rahul's answer might 'slip' if the timeout were delayed for whatever reason.

Peter Hull
  • 6,683
  • 4
  • 39
  • 48