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>
2
  • Do you want this :stackoverflow.com/questions/5517597/… ? Commented Apr 29, 2013 at 14:22
  • Could you post what you did try, then we can see if it can be fixed! Commented Apr 29, 2013 at 14:25

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Thanks, will try your version.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.