Reputation: 39
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>
Upvotes: 0
Views: 816
Reputation: 7067
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"> </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.
Upvotes: 1
Reputation: 5625
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
Upvotes: 1