Countdown with stop button - javascript

I tried to build a countdown timer and it kind of worked, but when I changed the code to make it more readable and when I added the stop button function it got a bit buggy. I fiddled around a lot, but I can't get it working again.
The problem I have is, that the countdown starts from the time when the page has loaded and not from the number assigned to "sessTime".
Here is the code (i know it is a lot, sorry):
var startButton = document.getElementById('btnStart');
var stopButton = document.getElementById('btnStop');
var sessionTime = parseInt(document.getElementById('sessNum').innerHTML); //gets duration number
var sessLength = Date.parse(new Date()) + sessionTime * 60 * 1000;
startButton.onclick = function() {
if (!sessTimer) {
startButton.value="Stop";
var sessTimer = setInterval(runSess, 1000);
}else{
startButton.value="Start";
clearInterval(sessTimer);
}
};
function runSess() {
var timeLeft = sessLength - Date.parse(new Date());
var seconds = Math.floor((timeLeft / 1000) % 60);
var minutes = Math.floor((timeLeft / 1000 / 60) % 60);
var hours = Math.floor((timeLeft / (1000 * 60 * 60)) % 24);
document.getElementById("hours").innerHTML = ('0' + hours).slice(-2);
document.getElementById("minutes").innerHTML = ('0' + minutes).slice(-2);
document.getElementById("seconds").innerHTML = ('0' + seconds).slice(-2);
if (timeLeft <= 0) {
clearInterval(sessTimer);
}
}
This code is part of a codepen project of mine. Maybe the context helps to answer this question.
Thanks in advance, I really appreciate your help.

You have declared sessTimer inside the scope of your function.
startButton.onclick = function() {
if (!sessTimer) {
startButton.value="Stop";
var sessTimer = setInterval(runSess, 1000);
With the code above, every time you enter the function, sessTimer is undefined and you declare a new one. What you can do is the following :
var sessTimer = null;
startButton.onclick = function() {
if (!sessTimer) {
startButton.value="Stop";
sessTimer = setInterval(runSess, 1000);
}else{
startButton.value="Start";
clearInterval(sessTimer);
sessTimer = null;
}
};
Into you function, you also need to change your button :
if (timeLeft <= 0) {
startButton.value="Start";
clearInterval(sessTimer);
}

Related

Make Countdown Timer 2 Digits For HH:MM:SS [duplicate]

This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Closed 2 years ago.
So, I am a novice in Javascript and I am wondering if someone can help me with this. I believe this question is really really easy for most. Well, this is a countdown timer with select options to set up the time. It is working well. The problem is that, when the countdown starts, I want the single digit numbers to show the number zero first. Basically, I want the numbers for HH:MM:SS to be 2 digits. For example, 00:01:59 and not 0:1:59. I believe it has something to do with padString or something (I could be wrong), but my proficiency is still no that advanced.
Note: I would highly appreciate it if we can come up with a Vanilla Javascript solution and not JQuery simply because I want to use this offline and without any online dependencies. Thank you in advance.
Javascript
<script>
var hours = 0;
var minutes = 0;
var seconds = 0;
var interval = null;
document.getElementById('hours').addEventListener('change', e => {
hours = +e.target.value;
});
document.getElementById('minutes').addEventListener('change', e => {
minutes = +e.target.value;
});
document.getElementById('seconds').addEventListener('change', e => {
seconds = +e.target.value;
});
document.getElementById('startTimer').addEventListener('click', () => {
var timeInSeconds = (hours * 60 * 60) +
(minutes * 60) +
seconds;
const audio = new Audio("audioURL.mp3");
var displayTime = () => {
var displayHours = Math.floor(timeInSeconds / (60 * 60));
var remainder = timeInSeconds - (displayHours * 60 * 60);
var displayMinutes = Math.floor(remainder / 60);
var displaySeconds = remainder - (displayMinutes * 60);
document.getElementById("timer").innerHTML = displayHours + ":" +
displayMinutes + ":" + displaySeconds;
};
interval = setInterval(() => {
displayTime();
timeInSeconds -= 1;
if (timeInSeconds < 0) {
clearInterval(interval);
audio.play();
}
}, 1000);
});
</script>
You could use ('0' + myValue).substr(-2) to fix the length with 2 characters. In this case '01' would be stay as '01' and '012' will be '12' because the -2 will cut the string from the end. Then your code will be:
var hours = 00;
var minutes = 00;
var seconds = 00;
var interval = null;
document.getElementById('hours').addEventListener('change', e => {
hours = +e.target.value;
});
document.getElementById('minutes').addEventListener('change', e => {
minutes = +e.target.value;
});
document.getElementById('seconds').addEventListener('change', e => {
seconds = +e.target.value;
});
document.getElementById('startTimer').addEventListener('click', () => {
var timeInSeconds = (hours * 60 * 60) +
(minutes * 60) +
seconds;
const audio = new Audio("audioURL.mp3");
var displayTime = () => {
var displayHours = Math.floor(timeInSeconds / (60 * 60));
var remainder = timeInSeconds - (displayHours * 60 * 60);
var displayMinutes = Math.floor(remainder / 60);
var displaySeconds = remainder - (displayMinutes * 60);
document.getElementById("timer").innerHTML = ('0' + displayHours).substr(-2) + ":" +
('0' + displayMinutes).substr(-2) + ":" + ('0' + displaySeconds).substr(-2);
};
interval = setInterval(() => {
displayTime();
timeInSeconds -= 1;
if (timeInSeconds < 0) {
clearInterval(interval);
audio.play();
}
}, 1000);
});

Make coutdown use localStorage

I am struggling to make this code to work with localStorage so if anyone can help me that would be amazing. How do I implement a localStorage in order to save the countdown when refreshing the page?
var hour = 5 * 3600;
var minute = 5 * 60;
var deadline = hour + minute;
function formatTime(seconds) {
var hide = false;
var h = Math.floor(seconds / 3600),
m = Math.floor(seconds / 60) % 60;
return h + m;
}
var counter = setInterval(timer, 1000);
function timer() {
deadline--;
if (deadline < 0) {
return clearInterval(counter);
}
$('#deadline').html(formatTime(deadline));
}
Store the value in the localStorage everytime the value gets decreased.
When you reload the page, check if the stored time exists, if yes store it in your deadline variable, otherwise let the deadline be the initial one.
var hour = 5 * 3600;
var minute = 5 * 60;
var deadline = hour + minute;
function formatTime(seconds) {
var hide = false;
var h = Math.floor(seconds / 3600),
m = Math.floor(seconds / 60) % 60;
console.log(h)
console.log(m)
return h + m;
}
var counter;
var storedTime = localStorage.getItem('deadline')
if (storedTime) {
deadline = Number(storedTime)
}
counter = setInterval(timer, 1000);
function timer() {
--deadline;
localStorage.setItem('time', deadline);
if (deadline < 0) {
return clearInterval(counter);
}
$('#deadline').html(formatTime(deadline));
}

javascript countdown echoing wrong time

i want this my javascript code to to be able to be reading 3 hours countdown and also redirect to a new page after the countdown is complete
<script type="text/javascript">
// properties
var count = 0;
var counter = null;
window.onload = function() {
initCounter();
};
function initCounter() {
// get count from localStorage, or set to initial value of 1000
count = getLocalStorage('count') || 1000;
counter = setInterval(timer, 1000); //1000 will run it every 1 second
}
function setLocalStorage(key, val) {
if (window.localStorage) {
window.localStorage.setItem(key, val);
}
return val;
}
function getLocalStorage(key) {
return window.localStorage ? window.localStorage.getItem(key) : '';
}
function timer() {
count = setLocalStorage('count', count - 1);
if (count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;
document.getElementById("timer").innerHTML = hours + "hours " + minutes + "minutes and " + seconds + " seconds left to complete this transaction"; // watch for spelling
}
</script>
<div id="timer"></div>
please help me make it better by making it been able to countdown to three hour and also redirect to another page after the countdown is complete
You didn't properly set total time. You set it to 16 minutes instead of 3 hours. Here is the working code (try it on JSFiddle):
var time = 60 * 60 * 3;
var div = document.getElementById("timer");
var t = Date.now();
var loop = function(){
var dt = (Date.now() - t) * 1e-3;
if(dt > time){
doWhateverHere();
}else{
dt = time - dt;
div.innerHTML = `Hours: ${dt / 3600 | 0}, Minutes: ${dt / 60 % 60 | 0}, Seconds: ${dt % 60 | 0}`;
}
requestAnimationFrame(loop);
};
loop();
Also, do not use setInterval and setTimeout for precise timing. These functions are volatile. Use Date.now() instead.

My javascriptcode is working when i put alert.I need to Display time in Counter Format(Seconds decreasing way)

My javascriptcode is working fine when i put alert.I need to Display time in Counter Format(Second decreasing way). Please help me in resolving this issue
<script type="text/javascript">
window.onload = function () {
//alert("request>>>");
var count = 0;
var start_actual_time = document.getElementById("timerStartTime").value;
var end_actual_time = document.getElementById("timerEndTime").value;
start_actual_time = new Date(start_actual_time);
var start_actual_time1 = new Date(start_actual_time.getTime());
start_actual_time1 = new Date(start_actual_time1);
var end_actual_time1 = new Date(end_actual_time);
var hours =end_actual_time1.getHours()- start_actual_time1.getHours();
var minutes = end_actual_time1.getMinutes() - start_actual_time1.getMinutes();
var seconds = end_actual_time1.getSeconds()- start_actual_time1.getSeconds();
seconds = hours * 3600 + minutes * 60 + seconds;
//alert ("seconds >>." +seconds);
timer(seconds);
};
function timer(seconds) {
alert("calling timer");
var s1 = Number(seconds);
var hours = Math.floor(s1 / 3600);
var minutes = Math.floor(s1 % 3600 / 60);
var s = Math.floor(s1 % 3600 % 60);
//alert("sec1" + s);
display = document.querySelector('#time');
var formatted = ((hours < 10)?("0" + hours):hours) + ":" + ((minutes < 10)?("0" + minutes):minutes) + ":" + ((s < 10)?("0" + s):s)
display.textContent = formatted ;
seconds = seconds - 1;
timer(seconds);
}
</script>
The way your code is written creates a
too much recursion
exception for me.
Therefore I have avoided recursive invokes and used javascript setInterval:
var refreshIntervalId = setInterval(function(){ timer(); }, 1000);
When your seconds reach zero, timer is stopped:
if (seconds == -1){
clearInterval(refreshIntervalId);
Link to working fiddle: http://jsfiddle.net/3ggspruf/2/

Javascript Undefined Variable Before Function

I have this chunk of javascript that's kind of hacked around from http://www.developphp.com/view.php?tid=1248 and I am seeing an error of "undefined variable - broadcast".
function cdtd(broadcast) {
/* expected date format is Month DD, YYYY HH:MM:SS */
var nextbroadcast = new Date(broadcast);
var now = new Date();
var timeDiff = nextbroadcast.getTime() - now.getTime();
if (timeDiff <= 0) {
clearTimeout(timer);
document.getElementById("countdown").innerHTML = "<a href=\"flconlineservices.php\">Internet broadcast in progress<\/a>";
/* Run any code needed for countdown completion here */
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
document.getElementById("daysBox").innerHTML = days + " d";
document.getElementById("hoursBox").innerHTML = hours + " h";
document.getElementById("minsBox").innerHTML = minutes + " m";
// seconds isn't in our html code (javascript error if this isn't commented out)
/*document.getElementById("secsBox").innerHTML = seconds + " s";*/
var timer = setTimeout('cdtd(broadcast)',1000);
}
"broadcast" is passed from the page with this <script type="text/javascript">cdtd("<?php echo $nextbroadcast; ?>");</script>. $nextbroadcast is based upon the date/time when the user views the page.
I tried var broadcast;, var broadcast = "";, and var broadcast = null;. Whenever I try to declare the variable, before the function, it breaks the script.
Am I doing something incorrectly? The script is working, just fine, but I'd rather not have the error.
Change the following line:
var timer = setTimeout('cdtd(broadcast)',1000);
To this:
var timer = setTimeout(function() { cdtd(broadcast); }, 1000);
This might be where the problem is:
var timer = setTimeout('cdtd(broadcast)',1000);
You should declare var timer; above cdtd() function, and then set it like so below or outside of the function:
var func = 'cdtd(' + broadcast + ')';
timer = setTimeout(func,1000);

Categories

Resources