JavaScript countdown timer counting past zero - javascript

This might be a really simple thing to ask but I've got a JavaScript countdown timer, but I can't stop it from counting past 0:00. Instead of stopping at this point, it will continue to -1:59 etc.
I'd also like it to play a beeping sound (which can be found here) when the timer reaches zero.
This is the code I've got so far:
<div class="stopwatch">
<div class="circle">
<div class="time" id="timer"></div>
</div>
</div>
<script>
document.getElementById('timer').innerHTML =
02 + ":" + 30;
startTimer();
function startTimer() {
var presentTime = document.getElementById('timer').innerHTML;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if(s==59){m=m-1}
document.getElementById('timer').innerHTML =
m + ":" + s;
console.log(m)
setTimeout(startTimer, 1000);
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {sec = "0" + sec}; // add zero in front of numbers < 10
if (sec < 0) {sec = "59"};
return sec;
}
</script>
Any help on this would be appreciated.

To stop the counter when it reaches zero you have to stop calling the startTimer() function. In the following snippet I have implemented a check to do exactly that.
function startTimer() {
var presentTime = document.getElementById('timer').innerHTML;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if(s==59){m=m-1}
document.getElementById('timer').innerHTML =
m + ":" + s;
console.log(m)
// Check if the time is 0:00
if (s == 0 && m == 0) { return };
setTimeout(startTimer, 1000);
}

Related

Repeat timer infinite amount of times

I am trying to add a countdown timer to my Shopify checkout using Google Optimize. I got this to work using the following HMTL & JS. Taken from here
However once the timer finishes and I reload the page it starts from 17 seconds instead of 5 minutes.
Is there a way to get this to repeat the timer from 5 minutes once it hits 0?
document.getElementById('timer').innerHTML =
05 + ":" + 00;
startTimer();
function startTimer() {
var presentTime = document.getElementById('timer').innerHTML;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if(s==59){m=m-1}
if(m<0){
return
}
document.getElementById('timer').innerHTML =
m + ":" + s;
console.log(m)
setTimeout(startTimer, 1000);
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {sec = "0" + sec}; // add zero in front of numbers < 10
if (sec < 0) {sec = "59"};
return sec;
}
<div>Your cart is reserved for <span id="timer"></span></div>
If you could give the answer like you are talking to a complete beginner it would be greatly appreciated.
Looks like I have a lot to learn!
Welcome to StackOverflow. This should help out...
//JAVASCRIPT
startTimer(5); // SPECIFY AMOUNT OF MINUTES OR NO PARAMETER FOR DEFAULT 5
function startTimer(minutes = 5){
var timeout = minutes * 60000;
var ms = timeout;
var interval = setInterval(function(){
ms -= 1000;
if(ms >= 0) {
var d = new Date(1000*Math.round(ms/1000));
document.getElementById('timer').innerHTML = getMS(d);
} else {
startTimer(5); // MAKE TIMER RESTART AGAIN FOR 5 MINS
// clearInterval(interval); // TO MAKE TIMER STOP UPON REACHING 0:00
}
}, 1000);
}
function getMS(d){
return pad(d.getUTCMinutes()) + ':' + pad(d.getUTCSeconds());
}
function pad(i) {
return ('0'+i).slice(-2);
}
<!--HTML -->
<body>
<div>Your cart is reserved for <span id="timer"></span></div>
</body>
In javascript the setInterval function allow you to make anything you want every fixed ms.
interval = setInterval(() => {
console.log('Waited for 5m');
// Do whatever you want
console.log('Waiting for 5m again...');
}, 300000);
// To stop the interval
clearInterval(interval);

Updating the button element as a countdown timer through javascript

I want to create a countdown timer which looks like an fps counter for webpage...
after hours of time spent i m not able to find out what is wrong.....help
<script>
var myvar = setInterval(function () { startTimer() }, 1000);
function startTimer() {
var presentTime = 17 + ":" + 00;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if (s == 59) {
m = m - 1
}
//if(m<0){alert('timer completed')}
var button2 = document.createElement("Button2");
var interval = m + s;
button2.innerHTML = Math.round(interval);
button2.style = "top:0; left:0rem; height:10% ;color: black; background-color: #ffffff;position:fixed;padding:20px;font-size:large;font-weight: bold;";
setTimeout(startTimer, 1000);
document.body.appendChild(button2);
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {
sec = "0" + sec
}; // add zero in front of numbers < 10
if (sec < 0) {
sec = "59"
};
return sec;
}
</script>
I can find three errors that hinder your code from performing correctly.
Multiple timers
First off since you invoke both a setInterval in outer scope, and then a setTimeout after each performed iteration, you will end up getting many unwanted timer instances that will do some crazy counting for you.
I recommend you to scrap either one of these and stick with just one of them.
For my example i happend to stick with the setInterval since you're executing the very same method over and over any way.
The initialization
Since the presentTime is declared inside the startTimer-function it will be constantly overwritten with 17 + ":" + 00 (resulting in "17:0" btw).
This is solved by declaring it in the outer scope instead.
Remembering the changes
Finally you need to save the current state of presentTime after modifications. Just adding a presentTime = [m,s].join(":"); at the end of startTimer() solves this.
var presentTime = "17:00";
function startTimer() {
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if (s == 59) {
m = m - 1
}
var button2 = document.createElement("Button2");
var interval = s;
button2.innerHTML = m + ":" + s;
button2.style = "top:0; left:0rem; height:10% ;color: black; background-color: #ffffff;position:fixed;padding:20px;font-size:large;font-weight: bold;";
document.body.appendChild(button2);
presentTime = [m,s].join(":");
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {
sec = "0" + sec
}; // add zero in front of numbers < 10
if (sec < 0) {
sec = "59"
};
return sec;
}
var interval = setInterval(startTimer, 1000);

Does `document.getElementById` break the function?

So I am working on a pomodoro timer and can't figure out what I am doing wrong with my JS. Overview of the project is here : http://codepen.io/Ohillio/pen/wMoNWy
But the specific part of the code I am having issues with is :
// global variables
var min = 0;
var sec = 0;
function tick() {
alert("Counter Started");
sec = 59;
min--;
document.getElementById("timer").innerHTML = min + ":" + sec;
do {
sec--
document.getElementById("timer").innerHTML = min + ":" + sec;
setTimeout(donothing,500);
}
while (sec != 0);
}
The issue is that it seems like it ends the function after the first time through. I want the seconds to tick down to 0, but now it just evaluates to 58.
Does document.getElementById break the function ?
Using setInterval may be a better solution to what you're trying to do. It's going to be more accurate and easy to short circuit once you hit 0. Also, I prefer to keep the total time in seconds and only use minutes for display purposes. I've put together an example for you to review.
<script>
var interval;
var totalSeconds = 1500;
function tick() {
totalSeconds--;
min = Math.floor(totalSeconds / 60);
sec = totalSeconds % 60;
document.getElementById('timer').innerHTML = min + ':' + sec;
if (0 >= totalSeconds) {
clearInterval(interval);
}
}
interval = setInterval(tick, 1000);
</script>
Hope this helps and good luck!
This also should work, with 1 digit second format fix:
var min = 1;
var sec = 30;
function tick() {
document.getElementById("timer").innerHTML = min + ":" + (sec.toString().length < 2 ? '0' : '') + sec;
if(sec === 0 && min > 0) {
min--;
sec = 59;
setTimeout(tick, 500);
} else if (sec > 0) {
sec--;
setTimeout(tick, 500);
} else {
alert("Done!");
}
}
alert("Counter Started");
tick();

Showing milliseconds in a timer html [duplicate]

This question already has answers here:
Adding milliseconds to timer in html
(2 answers)
Closed 8 years ago.
How do i show a countdown timer in html?
Current code:
var count=6000;
var counter=setInterval(timer, 1);; //1000 will run it every 1 second
function timer(){
count=count-1;
if (count <= 0){
clearInterval(counter);
return;
}
document.getElementById("timer").innerHTML=count + " milliseconds"; // watch for spelling
}
Converting seconds to ms
function msToTime(s) {
var ms = s % 1000;
s = (s - ms) / 1000;
var secs = s % 60;
s = (s - secs) / 60;
var mins = s % 60;
var hrs = (s - mins) / 60;
return hrs + ':' + mins + ':' + secs + '.' + ms;
}
How would i call out the timer?
still shows the timer as ms. i want it to show up as 99:00 seconds instead of 9900 milliseconds.
Thanks
You can do something like this:
var expires = new Date();
expires.setSeconds(expires.getSeconds() + 60); // set timer to 60 seconds
var counter = setInterval(timer, 1);
function timer() {
var timeDiff = expires - new Date();
if (timeDiff <= 0) {
clearInterval(counter);
document.getElementById("timer").innerHTML = "00:00";
return;
}
var seconds = new Date(timeDiff).getSeconds();
var milliSeconds = (new Date(timeDiff).getMilliseconds() / 10).toFixed(0);
var seconds = seconds < 10 ? "0" + seconds : seconds;
var milliSeconds = milliSeconds < 10 ? "0" + milliSeconds : milliSeconds;
document.getElementById("timer").innerHTML = seconds + ":" + milliSeconds; // watch for spelling
}
Here i set the start time from the javascript Date() function and then calculate the difference from current time in the timer() function.
Check it out here: JSFiddle
If it's JavaScript and has to do with Time I use moment.js
http://momentjs.com
Moment defaults to milliseconds as it's first parameter:
moment(9900).format("mm:ss"); Is 9 seconds, displayed as: 00:09
http://plnkr.co/edit/W2GixF?p=preview
Here's an actually accurate timer (in that it actually shows the correct amount of time left). setInterval will never call every 1 ms regardless of what you ask for because the actually resolution isn't that high. Nor can you rely on consistency because it's not running in a real-time environment. If you want to track time, compare Date objects:
var count=60000;
var start = new Date();
var counter=setInterval(timer, 1); //1000 will run it every 1 second
function timer(){
var left = count - (new Date() - start);
if (left <= 0){
clearInterval(counter);
document.getElementById("timer").innerHTML = msToTime(0) + " seconds";
return;
}
document.getElementById("timer").innerHTML = msToTime(left) + " seconds"; // watch for spelling
}
function msToTime(s) {
var ms = s % 1000;
s = (s - ms) / 1000;
return s + ':' + pad(ms, 3);
}
function pad(n, width, z) {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
<div id='timer'></div>
Borrowing from #Cheery's fiddle as a starting point.

Running a Javascript Clock at 4x Speed [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript to run the Clock (date and time) 4 times speeder
I'm trying to make a clock that starts at a time value (hh:mm:ss) that I've supplied, and runs at 4x speed (for the server time of an online game that runs 4x actual time). I've modified a free clock that I found online to do this, but it only works for every other minute (try the code below to see exactly what I mean if that doesn't make sense).
var customClock = (function () {
var timeDiff;
var timeout;
function addZ(n) {
return (n < 10 ? '0' : '') + n;
}
function formatTime(d) {
t1 = d.getHours();
t2 = d.getMinutes();
t3 = d.getSeconds() * 4;
if (t3 > 59) {
t3 = t3 - 60;
t2 = t2 + 1;
}
if (t2 > 59) {
t2 = t2 - 60;
t1 = t1 + 1;
}
if (t1 > 23) {
t1 = 0;
}
return addZ(t1) + ':' + addZ(t2) + ':' + addZ(t3);
}
return function (s) {
var now = new Date();
var then;
var lag = 1015 - now.getMilliseconds();
if (s) {
s = s.split(':');
then = new Date(now);
then.setHours(+s[0], +s[1], +s[2], 0);
timeDiff = now - then;
}
now = new Date(now - timeDiff);
document.getElementById('clock').innerHTML = formatTime(now);
timeout = setTimeout(customClock, lag);
}
}());
window.onload = function () {
customClock('00:00:00');
};
Any idea why this is happening? I'm pretty new to Javascript and this is definitely a little hack-ey. Thanks
i take the orginal time and substract it from the current then multiply it by 4 and add it to the orginal time. I think that should take care or the sync problem.
(function(){
var startTime = new Date(1987,08,13).valueOf() //save the date 13. august 1987
, interval = setInterval(function() {
var diff = Date.now() - startTime
//multiply the diff by 4 and add to original time
var time = new Date(startTime + (diff*4))
console.log(time.toLocaleTimeString())
}, 1000)
}())
How to use with a custom date (use the Date object)
Date(year, month, day, hours, minutes, seconds, milliseconds)
var lag = 1015 - now.getMilliseconds(); is attempting to "run this again a smidge (15 ms) after the next clock tick". Make this value smaller (divide by 4?), and this code will run more frequently.
Next up, get it to show 4x the current clock duration. Similar problem: multiply now's details by 4 either inside or outside formatTime()
I would first create a Clock constructor as follows:
function Clock(id) {
var clock = this;
var timeout;
var time;
this.hours = 0;
this.minutes = 0;
this.seconds = 0;
this.stop = stop;
this.start = start;
var element = document.getElementById(id);
function stop() {
clearTimeout(timeout);
}
function start() {
timeout = setTimeout(tick, 0);
time = Date.now();
}
function tick() {
time += 1000;
timeout = setTimeout(tick, time - Date.now());
display();
update();
}
function display() {
var hours = clock.hours;
var minutes = clock.minutes;
var seconds = clock.seconds;
hours = hours < 10 ? "0" + hours : "" + hours;
minutes = minutes < 10 ? "0" + minutes : "" + minutes;
seconds = seconds < 10 ? "0" + seconds : "" + seconds;
element.innerHTML = hours + ":" + minutes + ":" + seconds;
}
function update() {
var seconds = clock.seconds += 4;
if (seconds === 60) {
clock.seconds = 0;
var minutes = ++clock.minutes;
if (minutes === 60) {
clock.minutes = 0;
var hours = ++clock.hours;
if (hours === 24) clock.hours = 0;
}
}
}
}
Then you can create a clock and start it like this:
var clock = new Clock("clock");
clock.start();
Here's a demo: http://jsfiddle.net/Nt5XN/

Categories