Making a countdown timer?

ok, it seems to be working now, I didn’t realize I was only needed to declare the end variable in the global scope so it can be used by both functions

    function twoDigits( n )
    {
        return (n <= 9 ? "0" + n : n);
    }

//countdown timer function
var end = null;
function startTimer() {
	var startTime = document.getElementById("Timer_Start").value;

//check format for user input
	if( startTime.match(/^[0-9][0-9]:[0-9][0-9]:[0-9][0-9]$/)) {
	  document.getElementsByClassName("Error")[0].innerHTML = "";
	  document.getElementById("Timer_Form").style.display = "none";
	  document.getElementById("clockdiv").style.display = "block";
	  
	  var minutes = startTime.substr(0, 2);
	  var seconds = startTime.substr(3, 2);
	  var hundreths = startTime.substr(6,2);
	 
	  var start = new Date();
	  end = new Date(start.getTime() + minutes * 60 * 1000 + seconds * 1000 + hundreths * 10); 	
	  tick();
	} else {
	  document.getElementsByClassName("Error")[0].innerHTML = "Please use correct format (00:00:00)";
	  document.getElementById("Timer_Start").focus();
	}
}
var tick = function() {
  var curr = new Date();
  var ms = end.getTime() - curr.getTime();

  var minutes = Math.floor((ms / (60 * 1000)) % 60);
  var seconds = Math.floor((ms / 1000) % 60);
  var hundreths = Math.floor((ms / 10) % 60);
	if(ms <= 0) {
		clearInterval(tick);
		document.getElementById("clockdiv").innerHTML = "<h1>Times up!</h1>";
	} else {
		document.getElementById("clockdiv").innerHTML = "<h1>"+twoDigits(minutes) + ":" + twoDigits(seconds) +":"+twoDigits(hundreths)+"</h1>";
		setTimeout(tick, 10)
		
	}
}

now what were you saying mittineague?

This

var ms = end.getTime() - curr.getTime();

Getting a negative value is intended?

so I should change that to

var ms = Math.abs(end.getTime()) - Math.abs(curr.getTime());

end is a future time so it’s positive. My first example counted down to an earlier end time, but Paul suggested counting up to an end value.

so I should change that to…

No, if it’s working don’t change it.

2 Likes

ok
thanks all
JavaScript is a MMMAAADDD beast!

There’s an error in the code, you need to pass the timer created by setInterval to clearInterval

timer = setTimeout(tick, 10)
...
clearTimeout(timer)

I changed

setTimeout(tick, 10);
		

to

timer = setTimeout(tick, 10);
		clearTimeout(timer);

(no error though)
but now nothing seems to happen

clearTimeout(timer); needs to replace clearInterval(tick) and you’ll need to define var timer = null at the top.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.