I wrote code in JavaScript for a counter to be output in my HTML webpage, but nothing is being printed. Where is my logic wrong?
<script>
function calCountDown(){
var temp = new Date("Dec 11, 2022"); //makes an object 'temp' with current date and time
var deadline = temp.getTime(); //stores the deadline time
temp= new Date(); //stores the object of current date and time
var currentTime = temp.getTime(); //gets the current time
var timeDifference = deadline - currentTime;
var day = Math.floor(timeDifference / (1000*60*60*24)); //calculates the difference in days from today till deadline
var hour = Math.floor((timeDifference % (1000*60*60*24))/(1000*60*60)); //calculates the difference in hours from today till deadline
var minute = Math.floor((timeDifference % (1000*60*60))/(1000*60)); //calculates the difference in minutes from today till deadline
var sec = Math.floor((timeDifference % (1000*60))/1000); //calculates the difference in seconds from today till deadline
//THIS WILL OUTPUT THE TIME EVERYTIME THIS FUNCTION IS CALLED
document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
if(timeDifference < 0){
clearInterval(x);
document.getElementById("countdown").innerHTML = "ENDED !!!";
}
}
var x = setInterval(calCountDown(), 1000);
</script>
You have a couple of variables with incorrect names on this line:
document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
I think it should be:
document.getElementById("demo").innerHTML = day + "d " + hour + "h " + minute + "m " + sec + "s ";
Also, you had the same value on the deadline and currentTIme variables.
I have changed it on the example below, and you can see the it outputs the time to the #demo:
function calCountDown() {
var temp = new Date("Dec 11, 2022"); //makes an object 'temp' with current date and time
var deadline = temp.getTime(); //stores the deadline time
var currentTime = new Date(); //gets the current time
var timeDifference = deadline - currentTime;
var day = Math.floor(timeDifference / (1000 * 60 * 60 * 24)); //calculates the difference in days from today till deadline
var hour = Math.floor((timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); //calculates the difference in hours from today till deadline
var minute = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60)); //calculates the difference in minutes from today till deadline
var sec = Math.floor((timeDifference % (1000 * 60)) / 1000); //calculates the difference in seconds from today till deadline
//THIS WILL OUTPUT THE TIME EVERYTIME THIS FUNCTION IS CALLED
document.getElementById("demo").innerHTML = day + "d " + hour + "h " + minute + "m " + sec + "s ";
if (timeDifference < 0) {
clearInterval(x);
document.getElementById("countdown").innerHTML = "ENDED !!!";
}
}
var x = setInterval(calCountDown, 1000);
<p id="demo"></p>
Remove the () in your setInterval call:
var x = setInterval(calCountDown, 1000);
setInterval takes a function itself (or a string), you were passing it the return value from your function, which in this case is undefined.
For clarity, you were executing setInterval(undefined, 1000).
Further Opportunity to Learn
One of my most useful skills as a web developer is using the in-browser JavaScript debugger to step thru the code, set breakpoints, inspect variable values, etc.
I'd recommend you start using your JavaScript debugger to help understand what's going on in your code. Not just here, but any time you're not understanding what's going on in the code. Debuggers come with every major browser without needing any addons.
Related
I'm creating a javascript function to countdown a user selected value. This is my code so far.
function countdownTimeStart() {
var time = document.getElementById("test").value;
time = time.split(':');
var date = new Date();
var countDownDate = date.setHours(time[0], time[1], time[2]);
var x = setInterval(function () {
// Get to days date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
/* var distance = countDownDate;*/
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
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("demo1").innerHTML = hours + ": "
+ minutes + ": " + seconds + " ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo1").innerHTML = "00:00:00";
}
}, 200);
}
document.querySelector("button").addEventListener(
"click",
countdownTimeStart
)
<input type = "test" id = "test" value="20:12:40">
<div id="demo1"></div>
<button>start</button>
The problem is countdown is not working properly. The count down time start from another time instead of start from 20:12:40 which comes from input tag.
Please help me to solve this.
if you would like to count down a given time the following should work:
var time = document.getElementById("test").value;
time = time.split(':');
var date = new Date();
var countDownDate = date.setHours(time[0], time[1], time[2]);
function countdownTimeStart() {
var x = setInterval(function () {
// set hours, minutes and seconds, decrease seconds
var hours = time[0];
var minutes = time[1];
var seconds = time[2]--;
// if seconds are negative, set them to 59 and reduce minutes
if (time[2] == -1) {
time[1]--;
time[2] = 59
}
// if minutes are negative, set them to 59 and reduce hours
if (time[1] == -1) {
time[0]--;
time[1] = 59
}
// Output the result in an element with id="demo"
// add leading zero for seconds if seconds lower than 10
if (seconds < 10) {
document.getElementById("demo").innerHTML = hours + ": " + minutes + ": " + "0" + seconds + " ";
} else {
document.getElementById("demo").innerHTML = hours + ": " + minutes + ": " + seconds + " ";
}
}, 1000);
}
document.querySelector("button").addEventListener(
"click",
countdownTimeStart
)
<input type = "text" id = "test" value="20:00:01">
<div id="demo"></div>
<button>start</button>
Just set the countDownDate to the current time plus the number of hours, minutes, and seconds into the future you require.
var countDownDate = new Date( date.getTime()
+ parseInt(time[0])*(1000 * 60 * 60) //hours
+ parseInt(time[1])*(1000 * 60) //minutes
+ parseInt(time[2])*1000 ); //seconds
I alreay have some code for a countdown, but would like to make it pause for some hours when at 0 (with a text displayed), and then starts again for 14 days.
<script type="text/JavaScript">
var Display=document.getElementById("Counter");
function Countdown() {
var date1 = new Date();
var date2 = new Date ("Oct 20 20:00:00 2017");
var sec = (date2 - date1) / 1000;
var n = 24 * 3600;
if (sec > 0) {
j = Math.floor (sec / n);
h = Math.floor ((sec - (d * n)) / 3600);
mn = Math.floor ((sec - ((d * n + h * 3600))) / 60);
sec = Math.floor (sec - ((d * n + h * 3600 + mn * 60)));
Affiche.innerHTML = "Next game in : " + d +" d "+ h +" h "+ mn +" min "+ sec + " s ";
window.status = "Remaining time : " + d +" d "+ h +" h "+ mn +" min "+ sec + " s ";
}
tCountdown=setTimeout ("Countdown();", 1000);
}
Countdown();
</script>
So to sum up:
1. The countdown reach 0
2. It blocks for 4 hours and display a text ("We are currently playing")
3. It starts again for around 14 days.
I am thinking of something like this to start again the countdown:
var dateX = var date2 + (a length of time around 14 days)
Am I right?
Can I do this only with Javascript?
I broke it up into a bunch of functions so you can reason about it. If you want to test it, you can set the initial seconds in the sec variable to something small, like 10, and then you can also set the second argument in setTimeout to something small, like 10.
<div id="counter"></div>
<script>
// initialize
var first_target_date = new Date ("Oct 20 20:00:00 2017");
var sec = calcSecDiff(new Date(), first_target_date);
var counter = document.getElementById("counter");
var timeout; // we will update this global variable when we want to stop the whole thing
// start the countdown
countdown();
// do it again every second
var interval = setInterval(function(){
countdown();
}, 1000);
function countdown() {
counter.innerHTML = parseTime(sec);
// decrement the second
sec--;
// if we get to 0
if (sec < 0) {
clearInterval(interval);
counter.innerHTML = "We are currently playing";
if (timeout) return; // it's over
var timeout = setTimeout(function(){
sec = daysToSec(14); // reset the seconds to 14 days away
var interval = setInterval(function(){
countdown();
}, 1000);
}, hrsToMs(4)); // wait four hours before counting down again
};
}
// returns days, hours, minutes, and seconds from seconds
// see https://stackoverflow.com/questions/13903897/javascript-return-number-of-days-hours-minutes-seconds-between-two-dates
function parseTime(sec){
// calculate (and subtract) whole days
var days = Math.floor(sec / 86400);
sec -= days * 86400;
// calculate (and subtract) whole hours
var hours = Math.floor(sec / 3600) % 24;
sec -= hours * 3600;
// calculate (and subtract) whole minutes
var minutes = Math.floor(sec / 60) % 60;
sec -= minutes * 60;
// what's left is seconds
var seconds = sec % 60;
return days + " days, " + hours + " hours, " + minutes + " minutes, " + seconds + " seconds";
}
// calculates the difference between two dates in seconds
function calcSecDiff(date1, date2){
return Math.round((date2 - date1) / 1000);
}
// converts hours to milliseconds
function hrsToMs(hrs){
return hrs * 60 * 60 * 1000;
}
// converts days to seconds
function daysToSec(days){
return days * 24 * 60 * 60;
}
</script>
I have an issue in displaying counter between 2 dates. I know the issue and it is that Timezone is GMT+05:30
I need to know, how to rectify that
My Solution:
var start = new Date();
var end = new Date("2017-10-03"); // This date is coming from database as <?php echo $date_end; ?>
function getClock() {
var start = new Date();
var end = new Date("<?php echo $date_end; ?>");
var diff = Math.round((end.getTime() - start.getTime()) / 1000);
var hours = Math.floor(diff / 3600);
diff -= hours * 3600
var minutes = Math.floor(diff / 60);
diff -= minutes * 60;
var seconds = diff % 60;
if(document.getElementById('countdown')){
document.getElementById('countdown').innerHTML = "<span>"
+ hours + "</span> hours <span>" + minutes + "</span> minutes <span>"
+ seconds + "</span> seconds";
}
}
setInterval('getClock()', 1000);
As start date is 02 Oct 10PM and End date is 03 Oct. So as per time calculation i shall get timer of 2 hours
but i am getting timer is 2hours+5:30 = 7:30 hours.
Please help in getting right timer.
JS Fiddle link is HERE
You can get the timezone offset from the end date after you construct it, and then use that to reassign the value.
Here is a related question.
You can use the code from that post as follows:
var end = new Date("<?php echo $date_end; ?>");
end.setTime( end.getTime() + end.getTimezoneOffset()*60*1000 );
Try something like this.
setInterval(function(){
var start = new Date();
var end = new Date("2017-10-03 00:00:00");
var diff = Math.round((end.getTime() - start.getTime()) / 1000);
var hours = Math.floor(diff / 3600);
diff -= hours * 3600
var minutes = Math.floor(diff / 60);
diff -= minutes * 60;
var seconds = diff % 60;
if(document.getElementById('countdown')){
document.getElementById('countdown').innerHTML = "<span>"
+ hours + "</span> hours <span>" + minutes + "</span> minutes <span>"
+ seconds + "</span> seconds";
}
}, 1000);
The problem is because of the way Javascript handles timezones in the Date constructor (check out the documentation for details). If, instead of passing ("2017-10-03") you pass (2017, 9, 3), it should work. To avoid these kinds of problems, it is a good idea to always work in UTC.
Make sure you pass year, month and day separately to initialize the date, so the system timezone is used, same as when you initialize your start date:
var end_str = "<?php echo $date_end; ?>";
var arr = end_str.split("-")
arr = Date.new(arr[0], arr[1]-1, arr[2]); //month is 0-indexed
I am trying to make a countdown timer that will countdown to a certain date and time.
I would like to be able to set the date and time from a 'admin panel' by typing in the date and time(ex 2014-01-25, 15:00) in a textbox or something similar.
As you might've figured, I'm not the best at PHP or JavaScript and I'm in need of directions as of how I would do this.
Any help is appreciated as I haven't made any progress in the last 2 hours I've tried doing this.
To do this with no frameworks like JQuery, you can do the following:
var MINUTE_IN_MILLISECONDS = 60 * 1000;
var HOUR_IN_MILLISECONDS = 60 * MINUTE_IN_MILLISECONDS;
var YEAR_IN_MILLISECONDS = 24 * HOUR_IN_MILLISECONDS;
var targetDate = new Date('2014-01-25 15:00');
var countdownInterval;
function countdown(){
var currentDate = new Date();
var difference = targetDate.getTime() - currentDate.getTime();
//Countdown has expired, cancel interval and do other tasks here
if(difference <= 0)
{
difference = 0;
clearInterval(countdownInterval);
//Update button here
}
var days = Math.floor(difference / YEAR_IN_MILLISECONDS);
difference -= days * YEAR_IN_MILLISECONDS;
var hours = Math.floor(difference / HOUR_IN_MILLISECONDS);
difference -= hours * HOUR_IN_MILLISECONDS;
var minutes = Math.floor(difference / MINUTE_IN_MILLISECONDS);
difference -= minutes * MINUTE_IN_MILLISECONDS;
var seconds = Math.floor(difference / 1000);
console.log(days + ":" + hours + ":" + minutes + ":" + seconds);
}
countdownInterval = setInterval(countdown, 1000);
Here's the Fiddle
Full demonstration: http://jsfiddle.net/DerekL/T48SL/
<form>
<input type="date" required><input type="time" required>
<input type="submit">
</form>
<span></span>
$("form").on("submit", function (e) {
e.preventDefault();
var date = $("input[type=date]").val(),
time = $("input[type=time]").val(),
targetTime = new Date(date + " " + time),
interval = setInterval(function () {
$("span").html(
(((+startingTime - Date.now()) / 1000)|0) + " seconds left until " + startingTime.toString() + "."
);
}, 500);
});
It is fairly easy to format the time instead of just seconds with Algebra:
//yourTime is in seconds
(yourTime) % 60 //seconds
(yourTime / 60 |0) % 60 //minutes
(yourTime / 3600 |0) % 24 //hours
(yourTime / 86400 |0) //days
/*
* Explanation:
* % is mod, it finds the remainder of two numbers.
* |0 is binary OR, it rounds down a floating number.
*
*/
With this technique, you do not need to do a bunch of subtraction and create a lot of junk variables in the process.
So, I have the below (seconds countdown) in good order. But! I am trying to add hours & minutes as apart of the count down as well. Ideally keeping the same structure, and just using pure JS. I would like the output to be:
There is X hours, X minutes, and X seconds remaining on this Sale!
var count=30;
var counter=setInterval(timer, 1000); //1000 will run it every 1 second
function timer()
{
count=count-1;
if (count <= 0)
{
clearInterval(counter);
return;
}
document.getElementById("timer").innerHTML=count + " secs"; // watch for spelling
}
If the solution has to be a rewrite with jQuery or another library; that's fine. Just not preferable.
Cheers and Salutations for any help.
Something like this:
var count = 30;
var counter = setInterval(timer, 1000); //1000 will run it every 1 second
function timer() {
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 on this Sale!"; // watch for spelling
}
var totalSeconds = 3723; // lets say we have 3723 seconds on the countdown
// that's 1 hour, 2 minutes and 3 seconds.
var hours = Math.floor(totalSeconds / 3600 );
var minutes = Math.floor(totalSeconds % 3600 / 60);
var seconds = totalSeconds % 60;
var result = [hours, minutes, seconds].join(':');
console.log(result);
// 1:2:3
hours is seconds divided by the number of seconds in hour (3600) rounded down
minutes is the remainder of the above division, divided by the number of seconds in a minute (60), rounded down.
seconds is the remainder of total seconds divided by seconds in a minute.
Each calculation after hour has to use a modulus calculation to get the remainder, because you don't care about total time at that step, just progress to the next tick.
I would use a similar method to the others, but I wouldn't rely on setInterval / setTimeout as a timer, especially if users might be looking at the page for some time, as it tends to be inaccurate.
var endTime = new Date(2013, 10, 31).getTime() / 1000;
function setClock() {
var elapsed = new Date().getTime() / 1000;
var totalSec = endTime - elapsed;
var d = parseInt( totalSec / 86400 );
var h = parseInt( totalSec / 3600 ) % 24;
var m = parseInt( totalSec / 60 ) % 60;
var s = parseInt(totalSec % 60, 10);
var result = d+ " days, " + h + " hours, " + m + " minutes and " + s + " seconds to go!";
document.getElementById('timeRemaining').innerHTML = result;
setTimeout(setClock, 1000);
}
setClock();
This method calculates the difference between now and the date in the future each time it is run, thus removing any inaccuracies.
Here is an example: http://jsfiddle.net/t6wUN/1/