Multiple countdown timers using jQuery? - javascript

I'm trying to create multiple countdown timers using jQuery. The problem is that the numbers are not changing. Also, I'm not sure if this is the best way to do it. Any help is appriciated!
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/jquery#1.12.4/dist/jquery.min.js"></script>
<script>
$(document).ready(function() {
function countDown(id, date) {
var end = new Date(date);
end = (Date.parse(end) / 1000);
var now = new Date();
now = (Date.parse(now) / 1000);
var left = end - now;
var days = Math.floor(left / 86400);
var hours = Math.floor((left - (days * 86400)) / 3600);
var minutes = Math.floor((left - (days * 86400) - (hours * 3600 )) / 60);
var seconds = Math.floor((left - (days * 86400) - (hours * 3600) - (minutes * 60)));
$("#" + id).html(days + " days, " + hours + " hours, " + minutes + " minutes, " + seconds + " seconds");
}
$(".countdown").each(function() {
var init = setInterval(countDown($(this).attr("id"), $(this).data("date")), 1000);
});
});
</script>
</head>
<body>
<div class="countdown" id="1" data-date="2023-01-06 23:59:59"></div>
<div class="countdown" id="2" data-date="2023-01-07 23:59:59"></div>
<div class="countdown" id="3" data-date="2023-01-08 23:59:59"></div>
</body>
</html>

The problem you have is the way you use setInterval. The code is executing the function and what that function returns is set to the interval.
$(".countdown").each(function(elem) {
var init = setInterval(function() {
countDown($(elem).attr("id"), $(this).data("date"));
}, 1000);
});
Code with some things cleaned up:
$(document).ready(function() {
function countDown(elem, date) {
var end = new Date(date);
end = (Date.parse(end) / 1000);
var now = new Date();
now = (Date.parse(now) / 1000);
var left = end - now;
var days = Math.floor(left / 86400);
var hours = Math.floor((left - (days * 86400)) / 3600);
var minutes = Math.floor((left - (days * 86400) - (hours * 3600)) / 60);
var seconds = Math.floor((left - (days * 86400) - (hours * 3600) - (minutes * 60)));
elem.text(days + " days, " + hours + " hours, " + minutes + " minutes, " + seconds + " seconds");
}
$(".countdown").each(function() {
const elem = $(this);
var init = setInterval(function() {
countDown(elem, elem.data("date"));
}, 1000);
});
});
<script src="https://cdn.jsdelivr.net/npm/jquery#1.12.4/dist/jquery.min.js"></script>
<div class="countdown" id="1" data-date="2023-01-06 23:59:59"></div>
<div class="countdown" id="2" data-date="2023-01-07 23:59:59"></div>
<div class="countdown" id="3" data-date="2023-01-08 23:59:59"></div>

You may have the setInterval kicks in once only and dispatch an event that you previously chose to listen for on each of the element wrapping a datetime to countdown.
Here in this demo, on document ready it adds an event listener for the tick event on all the .countdown elements. The event handler will grab the data-date attribute value from the event.target and will replace its text content with the string returned by getTimeLeft(dategrabbed).
Next it will call setInterval once, with the callback in charge of dispatching the above defined event tick to all the interested elements .countdown so that they will all update their content.
function getTimeLeft(date) {
const now = new Date();
const before = new Date(date);
const left = (now.getTime() - before.getTime()) / 1000;
const days = Math.floor(left / 86400);
const hours = Math.floor((left - (days * 86400)) / 3600);
const minutes = Math.floor((left - (days * 86400) - (hours * 3600)) / 60);
const seconds = Math.floor((left - (days * 86400) - (hours * 3600) - (minutes * 60)));
return `${days} days, ${hours} hours, ${minutes} minutes, ${seconds} seconds`;
}
$(document).ready(()=>{
//listens for the tick event on all .countdown elements
$('.countdown').on('tick', (event)=>{
const startingDate = $(event.target).data("date");
const timeLeft = getTimeLeft(startingDate);
$(event.target).text(timeLeft);
})
//triggers the tick event to all the .countdown elements every second
setInterval(()=>{ $('.countdown').trigger('tick'); }, 1000);
});
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/jquery#1.12.4/dist/jquery.min.js"></script>
</head>
<body>
<div class="countdown" id="1" data-date="2023-01-06 23:59:59"></div>
<div class="countdown" id="2" data-date="2023-01-07 23:59:59"></div>
<div class="countdown" id="3" data-date="2023-01-08 23:59:59"></div>
</body>
</html>

Related

How i can create alert when time runs out in this code

Please help me with the code . How i can create alert when time runs out in this code. i want to set alert on when time runs out .
function makeTimer() {
// var endTime = new Date("29 April 2018 9:56:00 GMT+01:00");
var endTime = new Date("29 April 2020 9:56:00 GMT+01:00");
endTime = (Date.parse(endTime) / 1000);
var now = new Date();
now = (Date.parse(now) / 1000);
var timeLeft = endTime - now;
var days = Math.floor(timeLeft / 86400);
var hours = Math.floor((timeLeft - (days * 86400)) / 3600);
var minutes = Math.floor((timeLeft - (days * 86400) - (hours * 3600)) / 60);
var seconds = Math.floor((timeLeft - (days * 86400) - (hours * 3600) - (minutes * 60)));
if (hours < "10") {
hours = "0" + hours;
}
if (minutes < "10") {
minutes = "0" + minutes;
}
if (seconds < "10") {
seconds = "0" + seconds;
}
$("#minutes").html(minutes + "<span>Minutes</span>");
$("#seconds").html(seconds + "<span>Seconds</span>");
}
setInterval(function() {
makeTimer();
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="minutes"></span> <span id="seconds"></span>
Just test
const pad = n => ("0" + n).slice(-2);
var endTime = new Date();
// uncomment below
// endTime.setMinutes(endTime.getMinutes() + 15);// 15 minutes
// remove next line, it is just to show how the count down works without waiting 15 minutes
endTime.setSeconds(endTime.getSeconds() + 10);// 10 seconds
endTime = (Date.parse(endTime) / 1000);
function makeTimer() {
var now = new Date();
now = (Date.parse(now) / 1000);
var timeLeft = endTime - now;
var days = Math.floor(timeLeft / 86400);
var hours = Math.floor((timeLeft - (days * 86400)) / 3600);
var minutes = Math.floor((timeLeft - (days * 86400) - (hours * 3600)) / 60);
var seconds = Math.floor((timeLeft - (days * 86400) - (hours * 3600) - (minutes * 60)));
$("#minutes").html(pad(minutes) + " <span>Minute" + (minutes === 1 ? "" : "s") + "</span>");
$("#seconds").html(pad(seconds) + " <span>Second" + (seconds === 1 ? "" : "s") + "</span>");
if (seconds === 0 && minutes === 0) {
console.log("Done")
clearInterval(tId);
}
}
const tId = setInterval(makeTimer, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="minutes"></span> <span id="seconds"></span>
Inside the function,you can simply check the values of hours, minutes and seconds.As you already have it, you can simply put an if condition to check whether the hour is 0 and minute is 0 and second is 0. Then in that condition you can simply send an alert message.

How to stop a running countdown timer?

I've got a textbox and a button. Pressing it will calculate the time left based on the textbox value.
For example, for a value of 3600 (=seconds), it will calculate the left time : 0 days, 0 hours, 59 minutes 59 seconds.
Running the timer for the first time works greats, but I need it to reset and calculate time again from the second button pressing - and it's not working well. How can I stop the timer and run it again for new input values?
The code based on w3schhol example and another web example (you can test it):
// Set the date we're counting down to
function setTimer()
{
var timeSpan = convert();
//var countDownDate = new Date("Jan 5, 2021 15:37:25").getTime();
var countDownDate = new Date(timeSpan).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;
// 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);
}
function convert()
{
var now = new Date()
var secondsSinceEpoch = Math.round(now.getTime() / 1000)
// Unixtimestamp
var unixtimestamp = document.getElementById('timestamp').value;
unixtimestamp = parseInt(unixtimestamp);
secondsSinceEpoch = parseInt(secondsSinceEpoch);
unixtimestamp = unixtimestamp + secondsSinceEpoch;
// Months array
var months_arr = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
// Convert timestamp to milliseconds
var date = new Date(unixtimestamp*1000);
// Year
var year = date.getFullYear();
// Month
var month = months_arr[date.getMonth()];
// Day
var day = date.getDate();
// Hours
var hours = date.getHours();
// Minutes
var minutes = "0" + date.getMinutes();
// Seconds
var seconds = "0" + date.getSeconds();
// Display date time in MM-dd-yyyy h:m:s format
var convdataTime = month+' '+day+', '+year+' '+hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
//"Jan 5, 2021 15:37:25"
document.getElementById('datetime').innerHTML = convdataTime;
return convdataTime;
}
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
text-align: center;
font-size: 60px;
margin-top: 0px;
}
</style>
</head>
<body>
<input type='text' value='1490028077' id='timestamp'>
<input type='button' id='convert' value='Convert' onclick='setTimer()'>
<br><br>
<span id='datetime'></span>
<p id="demo"></p>
</body>
</html>
I tried to put a counter variable, and call return once the variable == 2 (return from
var x = setInterval(function()
)
But it didn`t work...
Here is an example:
var interval;
function setTimer()
{
clearInterval(interval)
var timeSpan = convert();
//var countDownDate = new Date("Jan 5, 2021 15:37:25").getTime();
var countDownDate = new Date(timeSpan).getTime();
// Update the count down every 1 second
interval = 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;
// 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(interval);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
}
function convert()
{
var now = new Date()
var secondsSinceEpoch = Math.round(now.getTime() / 1000)
// Unixtimestamp
var unixtimestamp = document.getElementById('timestamp').value;
unixtimestamp = parseInt(unixtimestamp);
secondsSinceEpoch = parseInt(secondsSinceEpoch);
unixtimestamp = unixtimestamp + secondsSinceEpoch;
// Months array
var months_arr = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
// Convert timestamp to milliseconds
var date = new Date(unixtimestamp*1000);
// Year
var year = date.getFullYear();
// Month
var month = months_arr[date.getMonth()];
// Day
var day = date.getDate();
// Hours
var hours = date.getHours();
// Minutes
var minutes = "0" + date.getMinutes();
// Seconds
var seconds = "0" + date.getSeconds();
// Display date time in MM-dd-yyyy h:m:s format
var convdataTime = month+' '+day+', '+year+' '+hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
//"Jan 5, 2021 15:37:25"
document.getElementById('datetime').innerHTML = convdataTime;
return convdataTime;
}
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
text-align: center;
font-size: 60px;
margin-top: 0px;
}
</style>
</head>
<body>
<input type='text' value='1490028077' id='timestamp'>
<input type='button' id='convert' value='Convert' onclick='setTimer()'>
<br><br>
<span id='datetime'></span>
<p id="demo"></p>
</body>
</html>
Here's an example of a class-based approach (so you don't need a global variable);
class Timer {
constructor(logTicks = false) {
this.interval = null;
this.logTicks = logTicks;
}
start() {
this.interval = setInterval( () => {
if (this.logTicks) { console.log('Tick'); }
}, 1000);
}
stop() {
if (this.interval) { clearInterval(this.interval); }
}
}
// Usage
const timer = new Timer(true);
timer.start();
setTimeout( () => { timer.stop(); }, 10000);

JavaScript countdown timer for hour, minutes and seconds when a start button click

I want to create countdown timer for hour,minute and second when a button click. This is my code so far.
HTMLcode
<div class="colomn" style="margin-right: 20px">
<button class="start" onclick="clock();">Start</button>
</div>
javascript function
<script>
var myTimer;
function clock() {
myTimer = setInterval(myClock, 1000);
var c = 5;
function myClock() {
document.getElementById("demo").innerHTML = --c;
if (c == 0) {
clearInterval(myTimer);
}
}
}
</script>
This is simple and not showing separate hour,min and sec. How can I apply this for count hour,min and sec. Please help me.
Working Code:
<!DOCTYPE HTML>
<html>
<body>
<p id="demo"></p>
<button onclick="countdownTimeStart()">Start Timer</button>
<script>
// Set the date we're counting down to
function countdownTimeStart(){
var countDownDate = new Date("Sep 25, 2025 15:00:00").getTime();
// 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 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 = 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>
</body>
</html>
Simple Answer would be as follows,
html part,
<button onclick="clockStart()">Start</button>
<p id="demo"></p>
JS part,
function clockStart() {
setInterval(function() {
date = new Date()
let hour = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();
document.getElementById("demo").innerHTML = hour + ":"+ minutes + ":" + seconds;
}, 1000);
}
You need a counter for seconds. During each 1 second interval, decrement this counter, and do the necessary calculations.
var myTimer;
function clock() {
myTimer = setInterval(myClock, 1000);
var c = 3610; //Initially set to 1 hour
function myClock() {
--c
var seconds = c % 60; // Seconds that cannot be written in minutes
var secondsInMinutes = (c - seconds) / 60; // Gives the seconds that COULD be given in minutes
var minutes = secondsInMinutes % 60; // Minutes that cannot be written in hours
var hours = (secondsInMinutes - minutes) / 60;
// Now in hours, minutes and seconds, you have the time you need.
console.clear();
console.log(hours + ":" + minutes + ":" + seconds)
if (c == 0) {
clearInterval(myTimer);
}
}
}
clock();
Put it in a fiddle as well. See if it works..
EDIT: Updated the erroneous code. Thanks to #JDrake for pointing the fact out...
You can convert the value in seconds to one in hours, minutes, and seconds:
var secs = Math.floor(c % 60);
var mins = Math.floor((c/60) % 60);
var hours = Math.floor((c/(60*60)));
This will yield you the amount of seconds left over when removing the minutes (using the modulus operator) and then repeats this for the minutes and hours. You can also easily extend this to include days or weeks:
var hours = Math.floor((c/(60*60)) % 24);
var days = Math.floor((c/(60*60*24) % 7);
var weeks = Math.floor((c/60*60*24*7));
Your code does suffer from one downside: if for some reason the calls become slightly further apart, this might increasingly build a delay. You might instead want to use the lines:
endTime = Date.parse(new Date()) + delay;
timeLeft = endTime - Date.parse(new Date());
You can try this;
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!-- This will start a timer for 5 hours 6 minutes and 7 seconds -->
<button onclick="countdown(5,6,7)"> Start </button>
<div><h3 id="timer"></h3></div>
<script>
function countdown(hr,mm,ss)
{
var interval = setInterval(function(){
if(hr == 0 && mm == 0 && ss == 0)clearInterval(interval);
ss--;
if(ss == 0)
{
ss = 59;
mm--;
if(mm == 0)
{
mm = 59;
hr--;
}
}
if(hr.toString().length < 2) hr = "0"+hr;
if(mm.toString().length < 2) mm = "0"+mm;
if(ss.toString().length < 2) ss = "0"+ss;
$("#timer").html(hr+" : "+mm+" : "+ss);
},1000)
}
</script>
Here is a very primordial clock for you:
function clock(t){
if(clock._stop){return};
var d = new Date(Date.now());
console.log(d.getHours()+":"+d.getMinutes()+":"+d.getSeconds()+":"+d.getMilliseconds())
window.requestAnimationFrame(clock);
}
clock._stop = false;
clock();
check your console. To stop the clock do clock._stop = true; To start it, set it back to false and call like clock(). You can wrap the logic inside an other object with getters/setters or whatever you prefer.
FIDDLE
var seconds_inputs = document.getElementsByClassName('deal_left_seconds');
var total_timers = seconds_inputs.length;
for ( var i = 0; i < total_timers; i++){
var str_seconds = 'seconds_'; var str_seconds_prod_id = 'seconds_prod_id_';
var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');
var cal_seconds = seconds_inputs[i].getAttribute('value');
eval('var ' + str_seconds + seconds_prod_id + '= ' + cal_seconds + ';');
eval('var ' + str_seconds_prod_id + seconds_prod_id + '= ' + seconds_prod_id + ';');
}
function timer() {
for ( var i = 0; i < total_timers; i++) {
var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');
var days = Math.floor(eval('seconds_'+seconds_prod_id) / 24 / 60 / 60);
var hoursLeft = Math.floor((eval('seconds_'+seconds_prod_id)) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = eval('seconds_'+seconds_prod_id) % 60;
function pad(n) {
return (n < 10 ? "0" + n : n);
}
document.getElementById('deal_days_' + seconds_prod_id).innerHTML = pad(days);
document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = pad(hours);
document.getElementById('deal_min_' + seconds_prod_id).innerHTML = pad(minutes);
document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(remainingSeconds);
if (eval('seconds_'+ seconds_prod_id) == 0) {
clearInterval(countdownTimer);
document.getElementById('deal_days_' + seconds_prod_id).innerHTML = document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = document.getElementById('deal_min_' + seconds_prod_id).innerHTML = document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(0);
} else {
var value = eval('seconds_'+seconds_prod_id);
value--;
eval('seconds_' + seconds_prod_id + '= ' + value + ';');
}
}
}
var countdownTimer = setInterval('timer()', 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" class="deal_left_seconds" data-value="1" value="8888888">
<div class="box-wrapper">
<div class="date box"> <span class="key" id="deal_days_1">00</span> <span class="value">DAYS</span> </div>
</div>
<div class="box-wrapper">
<div class="hour box"> <span class="key" id="deal_hrs_1">00</span> <span class="value">HRS</span> </div>
</div>
<div class="box-wrapper">
<div class="minutes box"> <span class="key" id="deal_min_1">00</span> <span class="value">MINS</span> </div>
</div>
<div class="box-wrapper hidden-md">
<div class="seconds box"> <span class="key" id="deal_sec_1">00</span> <span class="value">SEC</span> </div>
</div>
<!DOCTYPE HTML>
<html>
<body>
<p id="demo"></p>
<button onclick="countdownTimeStart()">Start Timer</button>
<script>
// Set the date we're counting down to
function countdownTimeStart(){
var countDownDate = new Date("Sep 25, 2025 15:00:00").getTime();
// 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 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 = 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>
</body>
</html>

How can i add the exact time to the date on countdown timer?

How can i add the exact time like "19:30" to the counter and still show "Tomorrow", "Today" and "Expired" messages?
Because when i add "19:30:00" the counter is not accurate.
When i use "Math.floor" instead of "Math.ceil" the counter is accurate but the messages not showen at the time they should.
<!DOCTYPE HTML>
<html>
<head>
<style>
p {
text-align: center;
font-size: 60px;
}
</style>
</head>
<body>
<p id="demo"></p>
<script>
// Set the date we're counting down to
var countDownDate = new Date("Dec 18, 2017 19:30:00").getTime();
// 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.ceil(distance / (1000 * 60 * 60 * 24));
var hours = Math.ceil((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.ceil((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.ceil((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
console.log(days);
if (days === 1) {
clearInterval(x);
document.getElementById("demo").innerHTML = "TOMORROW";
}
if (days === 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "TODAY";
}
if (days < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
</body>
</html>
This should work
// Set the date we're counting down to
var countDownDate = new Date("Dec 3, 2017 19:30: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 = countDownDate.getTime() - now.getTime();
// 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
console.log(days);
var tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
if (tomorrow.getFullYear() == countDownDate.getFullYear() && tomorrow.getMonth() == countDownDate.getMonth() && tomorrow.getDate() == countDownDate.getDate()) {
clearInterval(x);
document.getElementById("demo").innerHTML = "TOMORROW";
} else if (now.getFullYear() == countDownDate.getFullYear() && now.getMonth() == countDownDate.getMonth() && now.getDate() == countDownDate.getDate()) {
clearInterval(x);
document.getElementById("demo").innerHTML = "TODAY";
} else if (countDownDate.getTime() < now.getTime()) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
p {
text-align: center;
font-size: 60px;
}
<p id="demo"></p>

Pure JS countdown timer

I am trying to create a countdown timer, when i click on a button the timer will run according to the value 5, 15, 30 .
I could create a timer but my problem when using the set interval is i can't pass argument to the callback function, when i run the callback function with a preset value it runs fine, but when i am passing an argument it crashes,
var currentTime = new Date();
function displayCurrentTime() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var display = document.getElementById('now');
display.innerHTML = (hours + '.' + minutes + '.' + seconds);
return(new Date().getTime());
}
setInterval(displayCurrentTime, 1000);
function endTime(m) {
var display = document.getElementById('endTime');
var endingTime = new Date(currentTime.getTime() + (m * 60 * 1000));
var hours = endingTime.getHours();
var minutes = endingTime.getMinutes();
var seconds = endingTime.getSeconds();
display.innerHTML = (hours + '.' + minutes + '.' + seconds);
return endingTime.getTime();
}
function counter() {
var display = document.getElementById('counter');
var countingTime = endTime(1) - displayCurrentTime();
var days = Math.floor(countingTime / (1000 * 60 * 60 * 24));
var hours = Math.floor((countingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((countingTime % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((countingTime % (1000 * 60)) / 1000);
return (display.innerHTML = (hours + '.' + minutes + '.' + seconds));
}
<button id="5" onclick="setInterval(counter, 1000)">5</button>
<button id="15" onclick="setInterval(counter, 1000)">15</button>
<button id="30" onclick="setInterval(counter, 1000)">30</button>
<h3>Current Time</h3>
<p id="now"></p>
<h3>Your time will end at</h3>
<p id="endTime"></p>
<h3>You still have</h3>
<p id="counter"></p>
You can pass any arguments that you want after the delay param in the setInterval. Eg. setInterval(foo, 1000, bar). bar will be passed as a argument to foo every second.
I would simply set the end-time on click and start the counter. So your counter
var endTime = null;
function displayCurrentTime() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var display = document.getElementById('now');
display.innerHTML = (hours + '.' + minutes + '.' + seconds);
//just call counter here if endTime is set. in this case you only need to call updateEndTime on click
//if(endTime != null) {
// counter();
//}
}
//to avoid 1 second delay on start up
displayCurrentTime()
setInterval(displayCurrentTime, 1000);
function updateEndTime(m) {
var display = document.getElementById('endTime');
var currentTime = new Date();
endTime = new Date(currentTime.getTime() + (m * 60 * 1000));
var hours = endTime.getHours();
var minutes = endTime.getMinutes();
var seconds = endTime.getSeconds();
display.innerHTML = (hours + '.' + minutes + '.' + seconds);
}
function counter() {
var display = document.getElementById('counter');
var currentTime = new Date();
var countingTime = endTime - currentTime;
var days = Math.floor(countingTime / (1000 * 60 * 60 * 24));
var hours = Math.floor((countingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((countingTime % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((countingTime % (1000 * 60)) / 1000);
display.innerHTML = (hours + '.' + minutes + '.' + seconds);
}
<button id="5" onclick="updateEndTime(5);counter();setInterval(counter, 1000)">5</button>
<button id="15" onclick="updateEndTime(15);counter();setInterval(counter, 1000)">15</button>
<button id="30" onclick="updateEndTime(30);counter();setInterval(counter, 1000)">30</button>
<h3>Current Time</h3>
<p id="now"></p>
<h3>Your time will end at</h3>
<p id="endTime"></p>
<h3>You still have</h3>
<p id="counter"></p>
Btw. you probably should only use 1 setInterval and update both counters in 1 call checking if endTime is set or not

Categories

Resources