Skip to content

Instantly share code, notes, and snippets.

@maxcal
Created March 1, 2012 10:46
Show Gist options
  • Select an option

  • Save maxcal/1949018 to your computer and use it in GitHub Desktop.

Select an option

Save maxcal/1949018 to your computer and use it in GitHub Desktop.
javascript-countdown
/**
* @project: Countdown timer
* @author: Max Calabrese
* A eval free version of Dejan Jacimovic´s http://stuntsnippets.com/javascript-countdown/
*
* @licence:
* GNU / GPLv3
* You should have received a copy of the GNU General Public License
* If not, see <http://www.gnu.org/licenses/>.
*
* The Software shall be used for Good, not Evil.
**
var javascript_countdown = function () {
var time_left = 10, //number of seconds for countdown
output_element_id = 'javascript_countdown_time',
keep_counting = 1,
no_time_left_message = 'No time left for JavaScript countdown!';
function countdown() {
if(time_left < 2) {
keep_counting = 0;
}
time_left = time_left - 1;
}
function add_leading_zero(n) {
if(n.toString().length < 2) {
return '0' + n;
} else {
return n;
}
}
function format_output() {
var hours, minutes, seconds;
seconds = time_left % 60;
minutes = Math.floor(time_left / 60) % 60;
hours = Math.floor(time_left / 3600);
seconds = add_leading_zero( seconds );
minutes = add_leading_zero( minutes );
hours = add_leading_zero( hours );
return hours + ':' + minutes + ':' + seconds;
}
function show_time_left() {
document.getElementById(output_element_id).innerHTML = format_output();//time_left;
}
function no_time_left() {
document.getElementById(output_element_id).innerHTML = no_time_left_message;
}
return {
count: function () {
countdown();
show_time_left();
},
timer: function () {
javascript_countdown.count();
if(keep_counting) {
// Modified to get rid of evel
setTimeout(function(){ javascript_countdown.timer(); }, 1000);
} else {
no_time_left();
}
},
//Kristian Messer requested recalculation of time that is left
setTimeLeft: function (t) {
time_left = t;
if(keep_counting == 0) {
javascript_countdown.timer();
}
},
init: function (t, element_id) {
time_left = t;
output_element_id = element_id;
javascript_countdown.timer();
}
};
}();
//time to countdown in seconds, and element ID
javascript_countdown.init(3673, 'javascript_countdown_time');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment