Please i have a JavaScript countdown timer code that i got from stackoverflow that is a solution to my countdown timer project. this existing code counts down time from 30minutes down to 1 and start over again. and it gives the same count result to every user at the same time. But my challenge with the code is that i was not able to modify it in other to be able to regulate the count duration, because i want it to countdown from 2minutes to 0 and start over again continually,but not exceeding 2minutes. Please i need someone that will copy this code and run it a see if you can regulate the duration and help me with the solution. thanks in anticipation.
The code is as follows:
setInterval(function() { function addZero(i) { if (i < 10) { i = "0" + i; } return i; } var x = document.getElementById("timer"); var d = new Date(); var s = (d.getSeconds()); var m = (d.getMinutes()); var a = addZero(30 - m); var b = addZero(60 - m); var c = (60 - s); var z = "<span style='color:red;font-size:50px;'>" + "Break" + "</span>"; var v = "<span style='color:black;font-size:24px;'>" + "Break" + "</span>"; if (m > 30) { y = b; } else if (m < 30) { y = a; } if (y < 2 && c < 15) { q = z; } else { q = v; } var t = y + (":" + addZero(c) + " Till Station " + (q)); x.innerHTML = t; }, 250); <div align="center" id="timer" style='color:black;font-size:24px;' ></div>
Advertisement
Answer
The code you presented deserves a few remarks:
- Variable names should be descriptive, not one-letter a, b, c…
- Variables should be defined explicitly, not implicitly global, like now happens for
y
andq
- When
m
is 30, theny
does not get a value… this cannot be right. - If that last point would be corrected, then the logic for setting
z
would pose a new problem. - Styling should be done as much as possible via CSS classes, not via
style
attribute settings.
Here is how you could do it. You can set the first two constants to your liking:
// Maximum number of seconds for the timer (e.g. 120 = 2 minutes) const MAX_SECS = 120; // Number of seconds below which text gets highlighted const WARN_SECS = 15; // DOM const spanMinutes = document.getElementById("min"); const spanSeconds = document.getElementById("sec"); const spanWarning = document.getElementById("break"); // For formatting numbers with 2 digits const twoDigits = i => i.toString().padStart(2, 0); setInterval(() => { let seconds = MAX_SECS - Math.floor(Date.now() / 1000) % MAX_SECS; spanMinutes.textContent = twoDigits(Math.floor(seconds / 60)) spanSeconds.textContent = twoDigits(seconds % 60); spanWarning.classList.toggle("warn", seconds < WARN_SECS); }, 250);
#timer { text-align: center; font-size: 24px; } .warn { color: red; }
<div id="timer"><span id="min">00</span>:<span id="sec">00</span> till station <span id="break">breaks down</break> </div>