Created
February 24, 2011 19:42
-
-
Save mjangda/842737 to your computer and use it in GitHub Desktop.
A sweet js countdown timer with a custom callback that gives you a JSON object!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
timer('2011-12-31', function(timeRemaining) { | |
console.log('Timer 1:', timeRemaining); | |
}); | |
// This will run every minute, instead of every second | |
timer('2012-12-31', function(timeRemaining) { | |
console.log('Timer 2:', timeRemaining); | |
}, 60000); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* A sweet js countdown timer with a custom callback that gives you a JSON object! | |
* Heavily modified code originally found on http://www.ricocheting.com/code/javascript/html-generator/countdown-timer | |
* | |
* @param string|Date String representation of when to countdown to. Date objects probably work too | |
* @param callback Function triggered when the interval has passed | |
* @param int Number of milliseconds for the timeout. Defaults to 1000 (1 second) | |
* | |
* @return object Returns a JSON object with properties: days, hours, minutes, seconds | |
*/ | |
timer = function(endDate, callback, interval) { | |
endDate = new Date(endDate); | |
interval = interval || 1000; | |
var currentDate = new Date() | |
, millisecondDiff = endDate.getTime() - currentDate.getTime() // get difference in milliseconds | |
, timeRemaining = { | |
days: 0 | |
, hours: 0 | |
, minutes: 0 | |
, seconds: 0 | |
} | |
; | |
if(millisecondDiff > 0) { | |
millisecondDiff = Math.floor( millisecondDiff/1000 ); // kill the "milliseconds" so just secs | |
timeRemaining.days = Math.floor( millisecondDiff/86400 ); // days | |
millisecondDiff = millisecondDiff % 86400; | |
timeRemaining.hours = Math.floor( millisecondDiff/3600 ); // hours | |
millisecondDiff = millisecondDiff % 3600; | |
timeRemaining.minutes = Math.floor( millisecondDiff/60 ); // minutes | |
millisecondDiff = millisecondDiff % 60; | |
timeRemaining.seconds = Math.floor(millisecondDiff); // seconds | |
setTimeout(function() { | |
timer(endDate, callback); | |
}, interval); | |
} | |
callback(timeRemaining); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Where is the JSON in there ?