jQuery Count Down timer based on Remaining Days, Hours, Minutes and Seconds - javascript

I'm creating a system where I have to check the deadline based on the client's initialization. For example, if the client's initialization was today at time x and the deadline is tomorrow or future at time y, I would like to calculate the time remaining inform of a countdown timer. I have managed to get the time remaining and my problem is count down timer to show the remaining days, hours, minutes, and seconds.
The following HTML code indicates the remaining time to the deadline
<span style='color: green;'>
<span class='e-m-days'>0</span> Days |
<span class='e-m-hours'>8</span> Hours |
<span class='e-m-minutes'>0</span> Minutes |
<span class='e-m-seconds'>1</span> Seconds
</span>
My jQuery code:
<script>
$(function(){
var days = parseInt( $('.e-m-days').html() );
var hours = parseInt( $('.e-m-hours').html() );
var minutes = parseInt( $('.e-m-minutes').html() );
var seconds = parseInt( $('.e-m-seconds').html() );
var minutesWrap = 0;
var hoursWrap = 0;
var daysWrap;
var hoursRem = hours;
var timer = seconds;
var counter =seconds;
function countOrdersRemainingTime(){
var id = setTimeout(countOrdersRemainingTime, 1000);
if(timer < 0){
minutesWrap ++;
timer = 59;
}
var minRem = minutes - minutesWrap;
if( minRem == -1 ){
hoursWrap + 1;
minRem = 59;
var hoursRem = hours - 1;
}
if(days == 0 && hours == 0 && minutes == 0 && seconds == 0){
clearTimeout(id);
}
$('.e-m-seconds').html(timer);
$('.e-m-minutes').html(minRem);
$('.e-m-hours').html(hoursRem);
timer --;
}
countOrdersRemainingTime();
});
</script>
The key thing is to create a count down timer that counts until the deadline is reached, i.e until the number of days, hours, minutes, and seconds becomes zero. I have tried for hours with no success :(.

Consider the following example.
$(function() {
function getCounterData(obj) {
var days = parseInt($('.e-m-days', obj).text());
var hours = parseInt($('.e-m-hours', obj).text());
var minutes = parseInt($('.e-m-minutes', obj).text());
var seconds = parseInt($('.e-m-seconds', obj).text());
return seconds + (minutes * 60) + (hours * 3600) + (days * 3600 * 24);
}
function setCounterData(s, obj) {
var days = Math.floor(s / (3600 * 24));
var hours = Math.floor((s % (60 * 60 * 24)) / (3600));
var minutes = Math.floor((s % (60 * 60)) / 60);
var seconds = Math.floor(s % 60);
console.log(days, hours, minutes, seconds);
$('.e-m-days', obj).html(days);
$('.e-m-hours', obj).html(hours);
$('.e-m-minutes', obj).html(minutes);
$('.e-m-seconds', obj).html(seconds);
}
var count = getCounterData($(".counter"));
var timer = setInterval(function() {
count--;
if (count == 0) {
clearInterval(timer);
return;
}
setCounterData(count, $(".counter"));
}, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="counter" style='color: green;'>
<span class='e-m-days'>0</span> Days |
<span class='e-m-hours'>8</span> Hours |
<span class='e-m-minutes'>0</span> Minutes |
<span class='e-m-seconds'>1</span> Seconds
</div>
Based on: https://www.w3schools.com/howto/howto_js_countdown.asp

I believe this is what you're looking for. I've added comments to show exactly what's happening. Please let me know if anything isn't clear. I just picked a random date as a target date, but you can change it to anything you want :)
$(document).ready(function() {
const days = $(".e-m-days");
const hours = $(".e-m-hours");
const minutes = $(".e-m-minutes");
const seconds = $(".e-m-seconds");
const targetDate = new Date('May 17, 2020 03:24:00');
function convertMillis(milliseconds, format) {
var days, hours, minutes, seconds, total_hours, total_minutes, total_seconds;
total_seconds = parseInt(Math.floor(milliseconds / 1000));
total_minutes = parseInt(Math.floor(total_seconds / 60));
total_hours = parseInt(Math.floor(total_minutes / 60));
days = parseInt(Math.floor(total_hours / 24));
seconds = parseInt(total_seconds % 60);
minutes = parseInt(total_minutes % 60);
hours = parseInt(total_hours % 24);
switch(format) {
case 's':
return total_seconds;
case 'm':
return total_minutes;
case 'h':
return total_hours;
case 'd':
return days;
default:
return { d: days, h: hours, m: minutes, s: seconds };
}
};
window.setInterval( function()
{
// Where we check if 'now' is greater than the target date
var date = Date.now();
if (date > targetDate)
{
// Where we break
console.log("Expired");
clearInterval();
} else
{
// Where we set values
var millis = targetDate - date;
var millisObject = convertMillis(millis);
// Display values in HTML
days.text(millisObject.d);
hours.text(millisObject.h);
minutes.text(millisObject.m);
seconds.text(millisObject.s);
};
}, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span style='color: green;'>
<span class='e-m-days'>0</span> Days |
<span class='e-m-hours'>0</span> Hours |
<span class='e-m-minutes'>0</span> Minutes |
<span class='e-m-seconds'>0</span> Seconds
</span>

Related

Need to rebuild my countdown to output day(s) hour(s) etc

Countdown works fine but I need to output Text for exaple...
If 1 day is show then output Day if more days then Days, the same with hours, minutes and seconds..
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) {
function updateClock() {
const t = getTimeRemaining(endtime);
document.querySelector('.days').innerHTML = t.days;
document.querySelector('.hours').innerHTML = t.hours;
document.querySelector('.mins').innerHTML = t.minutes;
document.querySelector('.secs').innerHTML = ('0' + t.seconds).slice(-2);
if(t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
const timeinterval = setInterval(updateClock, 1000);
}
const countdown = "November 18 2022 19:00:00";
initializeClock("#codo", countdown);
1 Days 2 Hours 1 Minute 30 Seconds
I tried eg:
if(days > 1) { var day = 'Days'; } else { var day = 'Day'; }
But where exactly do I have to install it to output the text, I've tried a few things but non-stop initialize error given.
updateClock sets the output, specifically the 4 lines begining with document.querySelector. They set the content of 4 elements in your HTML.
function updateClock() {
const t = getTimeRemaining(endtime);
/* determine plural/singular word */
const days = t.days>1?" days":" day"
const hours = t.hours>1?" hours":" hour"
const minutes = t.minutes>1?" minutes":" minute"
const seconds = t.seconds>1?" seconds":" second"
/* append word to value */
document.querySelector('.days').innerHTML = t.days + days;
document.querySelector('.hours').innerHTML = t.hours + hours;
document.querySelector('.mins').innerHTML = t.minutes + minutes;
document.querySelector('.secs').innerHTML = ('0' + t.seconds).slice(-2) + seconds;
if(t.total <= 0) {
clearInterval(timeinterval);
}
}
innerHTML as the name suggests, sets the HTML inside the element. (as a string).
element.innerHTML = `Hello <div class="smallWord">World</div>`

Countdown Timer with Javascript (Repeating Weekly)

Here is the code I use to create a weekly repeating countdown timer. It works well, but I would like to expand on the following:
How can use this code twice on a single page without conflicts?
Currently, copying all elements and adjusting the "expiry" doesn't
work. I would like this to display two separate outputs with different expiry
dates.
Output is in the following format: hours, mins, and seconds. How can it
display only the most relevant information? For example, if there
are 10 hours 12 minutes, and 10 seconds left, it would display: 10
hours only(excluding mins and seconds). Similarly, if there were 00
hours 00 minutes and 10 seconds left it would instead display: 10
seconds (excluding mins and hours). The same would go for minutes (excluding hours and seconds).
Any insight would be most appreciated.
Repeating Countdown Timer Javascript
<script>
var curday;
var secTime;
var ticker;
function getSeconds() {
var nowDate = new Date();
var dy = 1 ; //Sunday through Saturday, 0 to 6
var countertime = new Date(nowDate.getFullYear(),nowDate.getMonth(),nowDate.getDate(),21,0,0); //20 out of 24 hours = 8pm
var curtime = nowDate.getTime(); //current time
var atime = countertime.getTime(); //countdown time
var diff = parseInt((atime - curtime)/1000);
if (diff > 0) { curday = dy - nowDate.getDay() }
else { curday = dy - nowDate.getDay() -1 } //after countdown time
if (curday < 0) { curday += 7; } //already after countdown time, switch to next week
if (diff <= 0) { diff += (86400 * 7) }
startTimer (diff);
}
function startTimer(secs) {
secTime = parseInt(secs);
ticker = setInterval("tick()",1000);
tick(); //initial count display
}
function tick() {
var secs = secTime;
if (secs>0) {
secTime--;
}
else {
clearInterval(ticker);
getSeconds(); //start over
}
var days = Math.floor(secs/86400);
secs %= 86400;
var hours= Math.floor(secs/3600);
secs %= 3600;
var mins = Math.floor(secs/60);
secs %= 60;
//update the time display
document.getElementById("days").innerHTML = curday;
document.getElementById("hours").innerHTML = ((hours < 10 ) ? "0" : "" ) + hours;
document.getElementById("minutes").innerHTML = ( (mins < 10) ? "0" : "" ) + mins;
document.getElementById("seconds").innerHTML = ( (secs < 10) ? "0" : "" ) + secs;
}
</script>
Call getSeconds() function to start timer with body onload
<body onload="getSeconds();">
</body>
Timer Display HTML
<h6>Live in <span class="days" id="days"></span><span class="smalltext"> days,</span>
<span class="hours" id="hours"></span><span class="smalltext"> hours,</span>
<span class="minutes" id="minutes"></span><span class="smalltext"> minutes</span>
</h6>
You can simply do it like this
//create a javascript timer function
function timerCountDOwn(date, id) {
const el = document.getElementById(id)
if (!el) return
let countDownDate = new Date(date).getTime()
const timer = setInterval(function () {
const now = new Date().getTime(),
distance = countDownDate - now,
days = Math.floor(distance / (1000 * 60 * 60 * 24)),
hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)),
seconds = Math.floor((distance % (1000 * 60)) / 1000),
//Format your output here
output = `<span class="days">${days}D</span> <span class="hours">${hours}H</span> <span class="minutes">${minutes}M</span> <span class="seconds">${seconds}S</span>`
el.innerHTML = output
if (distance < 0) {
clearInterval(timer)
el.innerHTML = 'EXPIRED'
}
}, 1000)
}
// then you can use it on multiple element in a single page
timerCountDOwn('Jan 5, 2023 00:00:00', 'timer1')
timerCountDOwn('Aug 25, 2022 00:00:00', 'timer2')
timerCountDOwn('Oct 30, 2022 15:22:54', 'timer3')
.timer > span {
display: inline-block;
background: #db0808;
color: #fff;
padding: 5px 10px;
border-radius: 5px;
}
<div id="timer1" class="timer">...</div>
<div id="timer2" class="timer">...</div>
<div id="timer3" class="timer">...</div>

Need to add 30 minutes timer into if condition using Js

I have ecommerce website. In that for same day delivery need to order before 11. So before 30 minutes of the end time(i.e. 11) i want to show that timer section.
Below code I am trying But getting issue how to set timer functionality.
setInterval(function(){
var secs = 1800;
var date = new Date;
// date.setTime(result_from_Date_getTime);
var seconds = date.getSeconds();
var minutes = date.getMinutes();
var hour = date.getHours();
console.log("Hour"+hour+"Minutes"+minutes+"seconds"+seconds);
// console.log(minutes);
// console.log(seconds);
if(hour == 10 && minutes>=30)
{
var mins = secs / 60;
console.log("Timer"+mins);
$('.top-header-content1').removeClass('hide-ticker1');
}
else if (hour >= 11){
console.log("hii11");
$('.top-header-content1').addClass('hide-ticker1');
}
secs--;
},1000);
If anyone have a idea , how to add time please let me know
Hi you use this code below:
/// the counting date
var countDownDate = new Date("Jan 5, 2024 15:37:25").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);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is finished
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<p id="demo"></p>
The following code will start a setInterval() in which during a time window between 10:30h and 11:00h a countdown will be shown. Before 10:30h and after 11:00h different messages are shown. And after 11:00h the setInterval is cleared.
// div for output on page:
const demo=document.getElementById("demo"),
// today's date
today = new Date();
today.setHours(11);today.setMinutes(0);today.setSeconds(0);
today.intv=setInterval(checkTime,1000);
function checkTime(){
const now=new Date();
if (now>today) {
demo.textContent="Order today for tomorrow's delivery.";
clearInterval(today.intv);
}
else if (now>(today-1800000)){
let tsec=Math.floor((today-now)/1000),
sec=tsec%60,
min=(tsec-sec)/60;
demo.textContent=`${min} minutes and ${sec} seconds left if you want to order for today's delivery.`;
} else
demo.textContent="Order now for today's delivery!"
}
<p id="demo"></p>

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);

Website Countdown js

Hi I am having a hard time making this countdown work for me. I am trying to make it count down to every sunday at 11:15am since that is when our church service starts. Can anyone pleaes help me? I have the code here.
function croAnim(){
// IF THERE'S A COUNTDOWN
if ($('ul.cro_timervalue').length !== 0) {
// GET ALL THE INSTANCES OF THE TIMER
$('ul.cro_timervalue').each(function() {
var $this = $(this),
timesets = $this.data('cro-countdownvalue'),
now = new Date(),
tset = Math.floor(now / 1000),
counter1 = timesets - tset;
// CALCULATE SECONDS
var seconds1 = Math.floor(counter1 % 60);
seconds1 = (seconds1 < 10 && seconds1 >= 0) ? '0'+ seconds1 : seconds1;
// CALCULATE MINUTES
counter1 =counter1/60;
var minutes1 =Math.floor(counter1 % 60);
minutes1 = (minutes1 < 10 && minutes1 >= 0) ? '0'+ minutes1 : minutes1;
// CALCULATE HOURS
counter1=counter1/60;
var hours1=Math.floor(counter1 % 24);
hours1 = (hours1 < 10 && hours1 >= 0) ? '0'+ hours1 : hours1;
// CALCULATE DAYS
counter1 =counter1/24;
var days1 =Math.floor(counter1);
days1 = (days1 < 10 && days1 >= 0) ? '0'+ days1 : days1;
// ADD THE VALUES TO THE CORRECT DIVS
$this.find('span.secondnumber').html(seconds1);
$this.find('span.minutenumber').html(minutes1);
$this.find('span.hournumber').html(hours1);
$this.find('span.daynumber').html(days1);
});
}
}
// CREATE A INTERVAL FOR THE TIMER
croInit = setInterval(croAnim, 100);
I answered a similar question about a week or so ago. I have a really simple countdown function already written. The trick is to modify it to get the next Sunday # 11:15 am, which I've written a function for.
var getNextSunday = function () {
var today = new Date(),
day = today.getDay(), // 1 for Mon, 2 for Tue, 3 for Wed, etc.
delta = 7 - day;
var sunday = new Date(today.getTime() + (delta * 24 * 3600 * 1000));
sunday.setHours(11);
sunday.setMinutes(15);
sunday.setSeconds(0);
return sunday;
}
var t = getNextSunday(),
p = document.getElementById("time"),
timer;
var u = function () {
var delta = t - new Date(),
d = delta / (24 * 3600 * 1000) | 0,
h = (delta %= 24 * 3600 * 1000) / (3600 * 1000) | 0,
m = (delta %= 3600 * 1000) / (60 * 1000) | 0,
s = (delta %= 60 * 1000) / 1000 | 0;
if (delta < 0) {
clearInterval(timer);
p.innerHTML = "timer's finished!";
} else {
p.innerHTML = d + "d " + h + "h " + m + "m " + s + "s";
}
}
timer = setInterval(u, 1000);
<h1 id="time"></h1>
This should be easy enough to adapt to fit your website's needs. The only tricky part might be my use of
h = (delta %= 24 * 3600 * 1000) / (3600 * 1000) | 0
delta %= ... returns delta, after performing the %=. This was just to save characters. If you don't like this, you can just separate the delta %= ... part:
delta %= 24 * 3600 * 1000;
h = delta / (3600 * 1000) | 0;
// ... do the same for the rest
This object uses a few semi-advanced javascript ideas (closures and * IIFE*) so hopefully it is easy-ish to understand. If you have any questions feel free to leave a comment.
var churchtime = (function (){
// Total seconds passed in the week by sunday 11:15am
var magic_number = 558900;
var now;
var rawtime = function (){
//updates now with the current date and time
now = new Date()
//Converts now into pure seconds
return (((((((now.getDay()-1)*24)+now.getHours())*60)+now.getMinutes())*60)+now.getSeconds());
};
//closure
return {
raw_countdown : function (){
return Math.abs(rawtime()-magic_number);
},
countdown : function(){
var time = Math.abs(rawtime()-magic_number)
var seconds = time % 60, time = (time - seconds)/60;
var minutes = time % 60, time = (time - minutes)/60;
var hours = time % 24, time = (time - hours)/24;
var days = time;
return [days,hours,minutes,seconds];
}
}
})(558900); //<- Total seconds passed in the week by sunday 11:15am
churchtime.raw_countdown()// returns the raw number of seconds until church
churchtime.countdown() // returns an array of time until church [days,hours,minutes,seconds]
Once you have an object like churchtime, it should be super easy to implement.
For example:
var churchtime = (function(magic_number) {
var now;
var rawtime = function() {
//updates now with the current date and time
now = new Date()
//Converts now into pure seconds
return (((((((now.getDay() - 1) * 24) + now.getHours()) * 60) + now.getMinutes()) * 60) + now.getSeconds());
};
//closure
return {
raw_countdown: function() {
return Math.abs(rawtime() - magic_number);
},
countdown: function() {
var time = Math.abs(rawtime() - magic_number)
var seconds = time % 60,
time = (time - seconds) / 60;
var minutes = time % 60,
time = (time - minutes) / 60;
var hours = time % 24,
time = (time - hours) / 24;
var days = time;
return [days, hours, minutes, seconds];
}
}
})(); //<- IIFE
AutoUpdate = function AutoUpdate() {
var time = churchtime.countdown();
document.getElementById("day").innerHTML = time[0];
document.getElementById("hour").innerHTML = time[1];
document.getElementById("min").innerHTML = time[2];
document.getElementById("sec").innerHTML = time[3];
setTimeout(AutoUpdate, 900); //Calls it's self again after .9 seconds
}(); //<- IIFE
<h1>Day:<span id="day"></span> Hour:<span id="hour"></span>
Minute:<span id="min"></span> second: <span id="sec"></span></h1>

Categories

Resources