This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 4 years ago.
I am trying to make a countdown timer in which the user can set day, hour, minute and seconds values.
The setlength() function takes the values from the textboxes then sets the variables.
Then when the user clicks the start button, the time in ms (variable lengthms) is calculated and added to the current time.
Then the countdown timer just counts down.
I am quite sure the counting down bit works but I don't understand/know why the script is unable to fetch the values from the input boxes and assign them to the variables.
Any help or another solution to varying the value of the hours minutes and seconds is appreciated.
Thank you in advance!
function setlength() {
var lengthd = document.getElementById("lengthd").value;
var lengthh = document.getElementById("lengthh").value;
var lengthm = document.getElementById("lengthm").value;
var lengths = document.getElementById("lengths").value;
}
function start() {
var lengthms = (lengthd * 24 * 3600 + lengthh * 3600 + lengthm * 60 + lengths * 1) * 1000;
var deadline = new Date(Date.parse(new Date()) + lengthms);
initializeClock('timerdiv', deadline);
}
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(id, endtime) {
var clock = document.getElementById(id);
var daysSpan = clock.querySelector('.days');
var hoursSpan = clock.querySelector('.hours');
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
function updateClock() {
var t = getTimeRemaining(endtime);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
var timeinterval = setInterval(updateClock, 500);
}
<!DOCTYPE html>
<html>
<body>
<h1>Countdown Timer</h1>
<div id="timerdiv">
<div>
<span class="days"></span>
<div class="smalltext">Days</div>
</div>
<div>
<span class="hours"></span>
<div class="smalltext">Hours</div>
</div>
<div>
<span class="minutes"></span>
<div class="smalltext">Minutes</div>
</div>
<div>
<span class="seconds"></span>
<div class="smalltext">Seconds</div>
</div>
</div>
<center>
<p id="length"></p>
Days: <input type="number" id="lengthd"> Hours: <input type="number" id="lengthh"> Minutes: <input type="number" id="lengthm"> Seconds: <input type="number" id="lengths"><br>
<button class="button set" onClick="setlength()">Set</button>
</center>
<center>
<div><button class="button start" onClick="start()">Start</button></div>
</center>
</body>
</html>
Your function setlength() declares all the lengths as local variables, so they are only usable from within that function.
Instead of
function setlength() {
var lengthd = document.getElementById("lengthd").value;
var lengthh = document.getElementById("lengthh").value;
var lengthm = document.getElementById("lengthm").value;
var lengths = document.getElementById("lengths").value;
}
you should declare the variables outside of your function
var lengthd;
var lengthh;
var lengthm;
var lengths;
function setlength() {
lengthd = document.getElementById("lengthd").value;
lengthh = document.getElementById("lengthh").value;
lengthm = document.getElementById("lengthm").value;
lengths = document.getElementById("lengths").value;
}
Note that I haven't checked the rest of your code, since you're sure that it works.
Related
i created this countdown that counts down 24 hours but once the page is refreshed,it restarts the countdown
how can i make it not start again?
please can anyone help me understand what i can do or to make it a static countdown
here are the codes
function getTimeRemaining(endtime) {
const total = Date.parse(endtime) - Date.parse(new Date());
const seconds = Math.floor((total / 1000) % 60);
const minutes = Math.floor((total / 1000 / 60) % 60);
const hours = Math.floor((total / (1000 * 60 * 60)) % 24);
const days = Math.floor(total / (1000 * 60 * 60 * 24));
return {
total,
days,
hours,
minutes,
seconds
};
}
function initializeClock(id, endtime) {
const clock = document.getElementById(id);
const daysSpan = clock.querySelector('.days');
const hoursSpan = clock.querySelector('.hours');
const minutesSpan = clock.querySelector('.minutes');
const secondsSpan = clock.querySelector('.seconds');
function updateClock() {
const t = getTimeRemaining(endtime);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
const timeinterval = setInterval(updateClock, 1000);
}
const deadline = new Date(Date.parse(new Date()) + 1 * 24 * 60 * 60 * 1000);
initializeClock('clockdiv', deadline);
<div>
<h1>Countdown Clock</h1>
<div id="clockdiv">
<div>
<span class="days"></span>
<div class="smalltext">Days</div>
</div>
<div>
<span class="hours"></span>
<div class="smalltext">Hours</div>
</div>
<div>
<span class="minutes"></span>
<div class="smalltext">Minutes</div>
</div>
<div>
<span class="seconds"></span>
<div class="smalltext">Seconds</div>
</div>
</div>
</div>
i'd really appreciate any help regarding this
I dont know what way to go about it
To not restart the countdown once the page is refreshed, the deadline data needs to be saved into a persistent storage that does not get cleared out even when the page is refreshed. You can achieve this by storing the deadline data in localStorage.
localStorage is similar to sessionStorage, except that while localStorage data has no expiration time, sessionStorage data gets cleared when the page session ends — that is, when the page is closed. - Source: LocalStorage
The change required on your code:
let deadline;
const prevDeadLine = localStorage.getItem("deadlineData"); // Get previous data from local storage
if (!prevDeadLine) {
deadline = new Date(Date.parse(new Date()) + 1 * 24 * 60 * 60 * 1000);
localStorage.setItem("deadlineData", deadline); // set the data for the first time
} else {
deadline = prevDeadLine; // use previousDeadline
}
Solution Snippet:
<html>
<head>
<title>
Countdown
</title>
</head>
<body>
<div>
<h1>Countdown Clock</h1>
<div id="clockdiv">
<div>
<span class="days"></span>
<div class="smalltext">Days</div>
</div>
<div>
<span class="hours"></span>
<div class="smalltext">Hours</div>
</div>
<div>
<span class="minutes"></span>
<div class="smalltext">Minutes</div>
</div>
<div>
<span class="seconds"></span>
<div class="smalltext">Seconds</div>
</div>
</div>
</div>
</body>
<script>
function getTimeRemaining(endtime) {
const total = Date.parse(endtime) - Date.parse(new Date());
const seconds = Math.floor((total / 1000) % 60);
const minutes = Math.floor((total / 1000 / 60) % 60);
const hours = Math.floor((total / (1000 * 60 * 60)) % 24);
const days = Math.floor(total / (1000 * 60 * 60 * 24));
return {
total,
days,
hours,
minutes,
seconds
};
}
function initializeClock(id, endtime) {
const clock = document.getElementById(id);
const daysSpan = clock.querySelector(".days");
const hoursSpan = clock.querySelector(".hours");
const minutesSpan = clock.querySelector(".minutes");
const secondsSpan = clock.querySelector(".seconds");
function updateClock() {
const t = getTimeRemaining(endtime);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ("0" + t.hours).slice(-2);
minutesSpan.innerHTML = ("0" + t.minutes).slice(-2);
secondsSpan.innerHTML = ("0" + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
} else {
new Date(Date.parse(new Date()) + 1 * 24 * 60 * 60 * 1000);
}
}
updateClock();
const timeinterval = setInterval(updateClock, 1000);
}
let deadline;
const prevDeadLine = localStorage.getItem("deadlineData");
if (!prevDeadLine) {
deadline = new Date(Date.parse(new Date()) + 1 * 24 * 60 * 60 * 1000);
localStorage.setItem("deadlineData", deadline);
} else {
deadline = prevDeadLine;
}
initializeClock("clockdiv", deadline);
</script>
</html>
I want to display this in several elements on the page. And it displays only once. In other elements it is empty. Do you have any solution regarding this issue?
Need to display it in a loop? Can you construct such a loop? As I created and wanted to display by class, no id unfortunately did not work.
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(id, endtime) {
var clock = document.getElementById(id);
var daysSpan = clock.querySelector('.days');
var hoursSpan = clock.querySelector('.hours');
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
function updateClock() {
var t = getTimeRemaining(endtime);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
function getNextSaturday() {
var now = new Date();
var nextSaturday = new Date();
nextSaturday.setDate(now.getDate() + (6 - 1 - now.getDay() + 7) % 7 + 1);
nextSaturday.setHours(11, 0, 0, 0);
return nextSaturday;
}
function convertToEST(date){
estOffset = -5.0
utc = date.getTime() + (date.getTimezoneOffset() * 60000);
return new Date(utc + (3600000 * estOffset));
}
var deadline = getNextSaturday();
initializeClock('clockdiv', convertToEST(deadline));
<h1>Countdown Clock</h1>
<div id="clockdiv">
<div>
<span class="days"></span>
<div class="smalltext">Days</div>
</div>
<div>
<span class="hours"></span>
<div class="smalltext">Hours</div>
</div>
<div>
<span class="minutes"></span>
<div class="smalltext">Minutes</div>
</div>
<div>
<span class="seconds"></span>
<div class="smalltext">Seconds</div>
</div>
</div>
Using the following JavaScript, how do I make it automatically restart the countdown adding 7 days when the deadline is reached?
(function($) {
"use strict";
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds,
};
}
function initializeClock(id, endtime) {
var daysSpan = $('.days');
var hoursSpan = $('.hours');
var minutesSpan = $('.minutes');
var secondsSpan = $('.seconds');
function updateClock() {
var t = getTimeRemaining(endtime);
daysSpan.html(t.days);
hoursSpan.html(('0' + t.hours).slice(-2));
minutesSpan.html(('0' + t.minutes).slice(-2));
secondsSpan.html(('0' + t.seconds).slice(-2));
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
var deadline = new Date("Aug 24, 2018");
initializeClock('clockdiv', deadline);
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="countdown">
<span class="days"></span> Days
<span class="hours"></span> Hours
<span class="minutes"></span> Minutes
<span class="seconds"></span> Seconds
</div>
why dont you just re-initialize the script with a new deadline?
if (t.total <= 0) {
clearInterval(timeinterval);
var newDeadline = deadline.setDate(deadline.getDate() + 7);
initializeClock('clockdiv', newDeadline);
}
i am trying below code for countdown to on exact date and time. I mean, i wants to make a under contractions website countdown date (include exact time). but date are not count downing. js code just showed me wrong count and not downing second, min, hours, day. This js code has problem, but i don't understand, exactly where is the problem.
Here is code:
(function init() {
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date("03/13/2018 9:30 AM"));
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(endtime){
var timeinterval = setInterval(function(){
var t = getTimeRemaining(endtime);
document.querySelector(".days > .value").innerText=t.days;
document.querySelector(".hours > .value").innerText=t.hours;
document.querySelector(".minutes > .value").innerText=t.minutes;
document.querySelector(".seconds > .value").innerText=t.seconds;
if(t.total<=0){
clearInterval(timeinterval);
}
},1000);
}
initializeClock(((new Date()).getFullYear()+1) + "/1/1")
})();
I made some modifications to your code.
I added a displayTime() function that handles the time display.
initializeClock() now calls displayTime() directly when it's called, without waiting one second.
getTimeRemaining() now calculates the right time, by taking the current date into account, and not a random date: var t = Date.parse(endtime) - Date.parse(new Date());
function displayTime(date){
var t = getTimeRemaining(date);
document.querySelector(".days > .value").innerText = t.days;
document.querySelector(".hours > .value").innerText = t.hours;
document.querySelector(".minutes > .value").innerText = t.minutes;
document.querySelector(".seconds > .value").innerText = t.seconds;
return t;
}
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(endtime) {
displayTime(endtime);
var timeinterval = setInterval(function() {
t = displayTime(endtime);
if (t.total <= 0) {
clearInterval(timeinterval);
}
}, 1000);
}
initializeClock("2018/03/13 09:30")
<div class="days"><span class="value"></span> days</div>
<div class="hours"><span class="value"></span> hours</div>
<div class="minutes"><span class="value"></span> minutes</div>
<div class="seconds"><span class="value"></span> seconds</div>
I think you are making this overly complicated. If you just start with a date and then every second, subtract one second from that start date, you're done.
var out = document.getElementById("output");
var start = new Date();
setInterval(function(){
start = new Date(start.getTime() - 1000);
out.textContent =
start.getHours() + " Hours, " + start.getMinutes() + " Minutes, " + start.getSeconds() + " Seconds";
},1000);
<div>Counting down from current time</div>
<span id="output"></span>
I am trying to make a timer start counting down. I think my next step is to make the countdown function to actually work. What would be the best approach for this?
JavaScript and HTML codes below:
// Set the default timer as 25:00
var timer = document.getElementById("mytime");
var counter = setInterval(function(){
countdown()}, 1000);
//user clicks the 'start' button and timer starts counting down
function countdown(minutes, seconds){
timer.value = "17:30:00"; //default value
document.getElementById("btn").innterHTML = counter;
counter--;
};
var click = document.getElementById("btn");
btn.addEventListener("click", countdown); //"click" as DOM Object?
btn.addEventListener("click", stopcounting);
<head>
<title>Pomodoro Timer</title>
</head>
<body>
<h1>POMODORO TIMER</h1>
<div id="main">
<input type="time" id="mytime">
<button id="btn"> start </button>
</div>
</body>
This is my own version of the clock where you can start the timer by adding the specific time when the event happened. Please see the below code.
// Set the date we're counting down to
var start_at = new Date('2020-06-29 12:00:00');
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date();
// Find the distance between now an the count down date
var distance = now - start_at;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").value = hours + "h "
+ minutes + "m " + seconds + "s ";
}, 1000);
This may be what you want, I haven't done it in the date time format but you can pretty much convert that by yourself.
<head>
<title>Pomodoro Timer</title>
</head>
<body>
<h1>POMODORO TIMER</h1>
<div id="main">
<input id="mytime" value=1000>
<button id="btn"> start </button>
</div>
</body>
<script>
var input = document.getElementById("mytime");
var button = document.getElementById("btn");
var started = false;
var timer;
var startTimer = function (count) {
return setInterval(function () {
input.setAttribute("value", --count);
}, 1000);
}
button.addEventListener("click", function () {
if (!started) {
var count = parseInt(input.getAttribute("value"));
timer = startTimer(count);
started = true;
button.innerHTML = "stop";
} else {
clearInterval(timer);
started = false;
button.innerHTML = "start";
}
});
</script>
JSFiddler: https://jsfiddle.net/m7pev0vm/
Your code is a bit jumbled. So let me help you sort it out.
First off, the click function needs to trigger a the start of countdown.
The counter in the timer function would need to be something in seconds. So that you can keep decrementing the value while on the face of it, it would be in hours, minutes & seconds.
Also, You need to have a target time. So if I say counter until 00:00:00 then the following could work, as an example :
// Set the default timer as 5:30 PM
var timer = document.getElementById("mytime");
var counter = (17*60*60) + (30*60);
timer.value = "17:30:00"; //default value
function countdown(minutes, seconds){
--counter;
var hrs = Math.floor(counter / 3600),
min = Math.floor((counter % 3600) / 60),
sec = Math.floor((counter % 3600) % 60);
timer.value = hrs + ":" + min + ":" + sec;
};
function onClick() {
var counter = setInterval(function(){
countdown();
}, 1000);
//user clicks the 'start' button and timer starts counting down
}
var click = document.getElementById("btn");
btn.addEventListener("click", onClick); //"click" as DOM Object?
btn.addEventListener("click", stopcounting);
<head>
<title>Pomodoro Timer</title>
</head>
<body>
<h1>POMODORO TIMER</h1>
<div id="main">
<input type="time" id="mytime">
<button id="btn"> start </button>
</div>
</body>
I know this is coming very late but I know it will help someone someday.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form>
<input type="text" name="demo" id="demo" size="20" readonly="true" style="text-align:center;"/>
<br>
</form>
<script>
// Set the date we're counting down to
var countDownDate = new Date().getTime() + ((1)*60*60*1000);
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").value = hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down remains 15 minutes, write some text
if (minutes == 59 && seconds == 1) {
alert("Hello! 1 minute gone");
}
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo");
demo.value= "EXPIRED";
}
}, 1000);
</script>
</body>
</html>