/** * Countdown from a given number. * * Usage: * var c = new Countdown(display,ondone,options); * c.start(10); * if (c.isRunning()) c.stop(); * c.resume(); * * Parameters: * display -- function to execute to display the count * or DOM element ID where count is to appear * or DOM element * ondone -- function to execute when countdown reaches 0 * or URL to redirect the browser when countdown is done * options -- optional options map * * Version 2.1 * Copyright 2006,2010, Mack Pexton, mackpexton.com * License http://www.opensource.org/licenses/mit-license.php */ (function(){ var default_options = { prefix: '', // prefix added to counter display suffix: '', // suffix added to counter display frequency: 1000, // 1 second in milliseconds }; var countdown = function(display,ondone,options) { if (typeof display == 'function') { this.display = display; } else { this.el = (typeof display == 'string') ? document.getElementById(display) : display; } this.ondone = ondone; this.options = {}; for (var p in default_options) { this.options[p] = default_options[p]; } if (options) { for (var p in options) { this.options[p] = options[p]; } } this.counter = 10; // arbitrary default for safety } countdown.prototype = { start: function(n) { if (this.timerID) this.stop(); if (n) this.counter = parseInt(n); var obj = this; var timer = function() { if (obj.display) obj.display(obj.counter); if (obj.el) obj.el.innerHTML = (obj.options.prefix ? obj.options.prefix : '') + obj.counter + (obj.options.suffix ? obj.options.suffix : ''); if (obj.counter <= 0) { obj.timerID = null; if (typeof obj.ondone == 'function') obj.ondone(obj.el); if (typeof obj.ondone == 'string') window.location.href = obj.ondone; return; } obj.timerID = setTimeout(arguments.callee,obj.options.frequency); obj.counter -= 1; } timer(); // start countdown }, stop: function() { if (this.timerID) { clearTimeout(this.timerID); this.timerID = null; } }, resume: function() { this.start(); }, isRunning: function() { return !!this.timerID; }, }; // Expose window.Countdown = countdown; })();