I recently worked on a project where the client wanted a constantly running 24 hour countdown. The countdown needed to reset automatically at 3pm and needed to be synced up with Eastern Standard Time (EST). I turned to the jQuery countdown plugin by Keith Wood.
This snippet will work out of the box with a few tweaks based on your current needs.
- Update the path to servertime.php (don’t forget to create this file and add the contents below)
- Update both times (current day and next day – lines 31 & 35)
- Update the class or id being targeted on line 48
That’s it!
jQuery(document).ready(function($) { | |
/* servertime.php | |
<?php | |
$now = new DateTime(); | |
echo $now->format("M j, Y H:i:s O")."\n"; | |
?> | |
*/ | |
jQuery(document).ready(function($) { | |
function serverTime() { | |
var time = null; | |
$.ajax({url: 'path-to/servertime.php', | |
async: false, dataType: 'text', | |
success: function(text) { | |
time = new Date(); | |
}, | |
error: function(http, message, exc) { | |
time = new Date(); | |
}}); | |
return time; | |
} | |
function getCountDown() { | |
var until = getNowEDT(); | |
until.setHours(15,0,0,0); // 3PM current day | |
if(getNowEDT() >= until){ | |
until.setHours(39,0,0,0); // 3PM next day | |
} | |
return until; | |
} | |
function getNowEDT() { | |
var now = new Date(); | |
now.setMinutes(now.getMinutes() + now.getTimezoneOffset() - 4 * 60); // EDT is UTC-4 | |
return now; | |
} | |
$('#home-timer').countdown({until: getCountDown(), compact: true, serverSync: serverTime, format: 'HMS', timezone: -4, | |
onExpiry: function() { | |
$(this).countdown('option', {until: getCountDown()}); | |
}}); | |
}); | |
// Another quick example of how to handle 24 hour countdown reset (without the timezone sync) | |
function doCountdown(){ | |
var todaysThree = new Date(), nextThree = new Date(); | |
todaysThree.setHours(15,0,0,0); | |
if (todaysThree <= nextThree){ nextThree.setDate(nextThree.getDate()+1); } | |
nextThree.setHours(15,0,0,0); | |
$('#home-timer').countdown({until: nextThree, compact: true, | |
description: '', onExpiry: function(){doCountdown()}}); | |
} | |
doCountdown(); | |
// http://keith-wood.name/countdownRef.html | |
// https://forum.jquery.com/topic/countdown-plugin-how-to-restart-countdown-timer-every-24-hours | |
}); |