Skip to content

Instantly share code, notes, and snippets.

@kennyray
Last active May 24, 2019 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kennyray/b35f4c6640be9539c5d16581de7714e0 to your computer and use it in GitHub Desktop.
Save kennyray/b35f4c6640be9539c5d16581de7714e0 to your computer and use it in GitHub Desktop.
Countdown timer
class CountdownTimer {
constructor(minutesLabel = null, secondsLabel = null) {
this.minutesLabel = minutesLabel;
this.secondsLabel = secondsLabel;
this.totalSeconds = (this.minutesLabel.textContent / 60) + this.secondsLabel.textContent;
this.timer = null;
}
set minutesLabel(value) {
this._minutesLabel = value;
}
set secondsLabel(value) {
this._secondsLabel = value;
}
get minutesLabel() {
return this._minutesLabel;
}
get secondsLabel() {
return this._secondsLabel;
}
setTime() {
this.totalSeconds--;
if (parseInt(this.minutesLabel.innerHTML) == 0 && parseInt(this.secondsLabel.innerHTML) == 0) { this.stopTimer; return;}
if (this.secondsLabel.innerHTML.textContent < 0) { this.secondsLabel.innerHTML = 59 }
if (this.minutesLabel.innerHTML.textContent < 0) { this.minutesLabel.innerHTML = 59 }
this.secondsLabel.innerHTML = this.pad((this.totalSeconds % 60));
this.minutesLabel.innerHTML = this.pad(Math.floor(this.totalSeconds / 60));
}
pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
resetTimer() {
clearInterval(this.timer);
this.totalSeconds = 0;
this.secondsLabel.innerHTML = this.pad(this.totalSeconds % 60);
this.minutesLabel.innerHTML = this.pad(parseInt(this.totalSeconds / 60));
}
startTimer() {
this.timer = setInterval(this.setTime.bind(this), 1000);
}
stopTimer() {
clearInterval(this.timer);
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Countdown Timer</title>
<script src="countdown_timer2.js"></script>
</head>
<body>
<label id="minutes1">00</label>:<label id="seconds1">10</label>
<br>
<label id="minutes">00</label>:<label id="seconds">09</label>
<script>
const t1 = new CountdownTimer(document.getElementById("minutes1"), document.getElementById("seconds1"));
//t1.startTimer();
const t2 = new CountdownTimer(document.getElementById("minutes"), document.getElementById("seconds"));
console.log(t1.startTimer() === t2.startTimer());
t2.startTimer();
</script
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment