I'm trying to make a countdown timer in JavaScript, specifically one that I can set to either one or two minutes, as well as when it starts.
This is what I've been able to accomplish from scratch, but I can't seem to get it to work:
var tim = 90
var min = (tim / 60) >> 0;
var sec = tim % 60;
function set1() {
tim=60;
}
function set2() {
tim=120;
}
function start() { function{ setInterval(function(){ tim-1; }, 1000);
}
function display() {
document.getElementById("demo").innerHTML = min + ":" + sec ;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body onload="display()">
<p id="demo"></p>
<button onclick="set1()"> set one minute</button>
<button onclick="set2()"> set two minute</button>
<button onclick="start()"> start </button>
</body>
</html>
I've also tried adapting the following solution from here, but to no avail.
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);
// does the same job as parseInt truncates the float
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (diff <= 0) {
// add one second so that the count down starts at the full duration
// example 05:00 not 04:59
start = Date.now() + 1000;
}
};
// we don't want to wait a full second before the timer starts
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
<body>
<div>Registration closes in <span id="time"></span> minutes!</div>
</body>
What am I missing here?