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
Related
I've found a timer countdown in javascript online and it works fine...
I have to pass python variable to it but, although the result is correct, the countdown doesn't run, it shows the correct remaining time but doesn't continue to decrease (at least I refresh the page)...
These are my piece of codes:
views.py
import datetime
auction = Auction.objects.get(id=id)
endDateFormat = auction.endDate.strftime("%Y-%m-%dT%H:%M:%S")
startDateFormat = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
template.html
<script>
// Set the date we're counting down to
var countDownDate = new Date("{{endDateFormat}}").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date("{{startDateFormat}}").getTime();
// Find the distance between now and 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").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
Thanks to everyone!
Try this! Given a view:
def timer_page_view(request):
auction = Auction.objects.last()
context = {
'start_date': auction.start_date.strftime("%Y-%m-%dT%H:%M:%S"),
'end_date': auction.end_date.strftime("%Y-%m-%dT%H:%M:%S"),
}
return render(request, 'timer_page.html', context=context)
Your timer_page.html template could look like this:
<body>
<p>start date is {{ start_date }}</p>
<p>start date is {{ end_date }}</p>
<div id='demo'>time difference</div>
</body>
<script>
// Set the date we are counting to
var countDownDate = new Date('{{ end_date }}');
// Set the date we are counting from
var countFromDate = new Date("{{ start_date }}");
// Set inital distance in seconds
var distance = (countDownDate.getTime() - countFromDate.getTime()) / 1000;
// Set initial time difference in the DOM
var days = Math.floor((distance / (60 * 60 * 24)));
var hours = Math.floor((distance - (days * (60 * 60 * 24))) / (60 * 60));
var minutes = Math.floor((distance - ((days * (60 * 60 * 24)) + (hours * (60 * 60)))) / 60);
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("demo").innerHTML = days + ' ' + hours + ' ' + minutes + ' ' + seconds;
// Timer
let active = true;
startTimer = () => {
if (active) {
var timer = document.getElementById("demo").innerHTML;
let nums = timer.split(" ").map(num => parseInt(num))
let day = nums[0];
let hour = nums[1];
let min = nums[2];
let sec = nums[3];
if (sec == 0) {
if (min == 0) {
hour--;
min = 59;
if (hour == 0){
day--;
hour = 23;
}
if (hour < 10) hour = "0" + hour;
} else {
min--;
}
if (min < 10) min = "0" + min;
sec = 59;
} else {
sec--;
console.log(sec)
if (sec < 10) sec = "0" + sec;
}
document.getElementById("demo").innerHTML = day + ' ' + hour + ' ' + min + ' ' + sec;
setTimeout(startTimer, 1000);
}
}
startTimer();
</script>
The timer would start immediately here, but you can play around with that to your liking.
I am trying to get the date to change to second date. On the first date, I would like it to show Starts: in bold and then the remaining time. I have it figured to change to a second date. When it changes to the second date, i want it to show Ends: in bold then the remaining time. When both countdown timers end, I want it to display text saying the event has ended. Here is what I have so far.
<script>
// Set the date we're counting down to
var countDownDate = new Date("July 23, 2020 21:07:00").getTime();
var countDownDate2 = new Date("July 23, 2020 21:08:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
var distance2 = countDownDate2 - now;
var a;
if (distance < 0 && distance2 >0) {
a = distance2;
} else {
a = distance;
}
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(a / (1000 * 60 * 60 * 24));
var hours = Math.floor((a % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((a % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((a % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = "Starts: " + days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// Change to another exp.
if (distance < 0 && distance2 >0) {
function changeDate() {
a = distance2;
}
}
// If the count down is over, write some text
if (distance2 < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}}, 1000);
</script>
It seems you basically have it figured out, if I'm understanding the question. You just need another variable for the Start/End label, and then use it when you set .innerHTML of the demo element.
<div id="demo"></div>
<script>
// Set the date we're counting down to
//var countDownDate = new Date("July 23, 2020 21:07:00").getTime();
var countDownDate = Date.now() + 5000; // using a shorter time for testing purposes;
// var countDownDate2 = new Date("July 23, 2020 21:08:00").getTime();
var countDownDate2 = Date.now() + 10000;
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
var distance2 = countDownDate2 - now;
var a;
var label = 'Starts: ';
if (distance < 0 && distance2 >0) {
a = distance2;
label = 'Ends: ';
} else {
a = distance;
}
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(a / (1000 * 60 * 60 * 24));
var hours = Math.floor((a % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((a % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((a % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = "<strong>" + label + "</strong>" + days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// Change to another exp.
if (distance < 0 && distance2 >0) {
function changeDate() {
a = distance2;
}
}
// If the count down is over, write some text
if (distance2 < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}}, 1000);
</script>
I have build a popup with a timer. When the timer ends I want it to extend itself with another day. I have gone so far that it extends itself with 1 day for 1 time but then it quits.
Maybe you have any idea on how to proceed?
Thanks!
//Make countdown
var setInfiniteTime = '{{ $actiepopup->infiniteTime }}';
// Update the count down every 1 second
var x = setInterval(function() {
// Set the date we're counting down to
// Get todays date and time
var currentDate = new Date().getTime();
// get countdown time
var countDownDate = new Date(countDownTimeUntil).getTime();
// console.log('countdowndateBefore' + countDownDate);
// check in infinite time is set
if (setInfiniteTime == 'Yes') {
if (currentDate >= countDownDate) {
// var i;
// for (var i = 0; i < 999999; i++) {
var countDownDate = new Date(countDownTimeUntil).getTime() + 86400000;
// console.log(i);
// }
}
}
// console.log('currentdate' + currentDate);
// console.log('countdowndate' + countDownDate);
// Find the distance between now and the count down date
var distance = countDownDate - currentDate;
// 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);
// Display the result in the element with id="countdown"
$("#countdown").text(days + "d " + hours + "h " + minutes + "m " + seconds + "s ");
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
$("#countdown").text("Actie beeïndigd");
}
}, delayInMilliseconds);
Hope you have enough information!
SetInterval()
Also, just an advice, if you use boolean statements, just use true or false since it's way easier to work with
if (setInfiniteTime) {
setInterval(() => {
var countDownDate = new Date(countDownTimeUntil).getTime() + 86400000
}, 86400000)
}
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 already tried many scripts, but result is not coming as required.
<script>
// Set the date we're counting down to
//var countDownDate = new Date("<?php echo $final_date; ?>").getTime();
var countDownDate = new Date("<?php echo $final_date; ?>").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
//var now = new Date().getTime();
//alert(now);
var offset = -7;
var get = new Date( new Date().getTime() + offset * 3600 * 1000).toUTCString().replace( / GMT$/, "" );
var now = new Date(get).getTime();
//alert(now);
// 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"
if(days == '0'){
document.getElementById("demo").innerHTML = hours + "hours "
+ minutes + "minutes " + seconds + "seconds ";
} else if(hours == '0') {
document.getElementById("demo").innerHTML = minutes + "minutes " + seconds + "seconds ";
} else if(minutes == '0') {
document.getElementById("demo").innerHTML = seconds + "seconds ";
} else if(seconds == '0') {
document.getElementById("demo").innerHTML = "";
} else {
document.getElementById("demo").innerHTML = days + "days " + hours + "hours "
+ minutes + "minutes " + seconds + "seconds ";
}
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "expired";
}
}, 1000);
</script>