Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A Very Simple - Timezone Agnostic - Countdown Script.
class window.Countdown
constructor: (ends_at, custom_callbacks) ->
now = new Date
end = new Date(Number(ends_at) * 1000)
default_callbacks =
tick: ->
complete: ->
@callbacks = $.extend(default_callbacks, custom_callbacks)
@difference = Math.ceil((end - now) / 1000)
@start()
start: ->
@interval_id = window.setInterval (=>
@tick()
), 1000
tick: ->
if @difference > 0
@difference--
@callbacks.tick
seconds: @pad(@difference % 60)
minutes: @pad(Math.floor(@difference / 60) % 60)
hours: Math.floor(@difference / 60 / 60) % 24
else
@stop()
pad: (number) ->
"0#{number}".slice(-2)
complete: (callback) ->
@stop()
@callbacks.complete()
stop: ->
window.clearInterval @interval_id
#######################################################################################
$ ->
countdown = new Countdown "1351090738", # winnable_at.to_i
tick: (date) ->
$('#countdown .timer .hours').text(date.hours)
$('#countdown .timer .minutes').text(date.minutes)
$('#countdown .timer .seconds').text(date.seconds)
complete: ->
# AJAX Request for results. Retry on 403.
console?.log? 'Countdown Complete'
window.Countdown = (function() {
function Countdown(ends_at, custom_callbacks) {
var default_callbacks, end, now;
now = new Date;
end = new Date(Number(ends_at) * 1000);
default_callbacks = {
tick: function() {},
complete: function() {}
};
this.callbacks = $.extend(default_callbacks, custom_callbacks);
this.difference = Math.ceil((end - now) / 1000);
this.start();
}
Countdown.prototype.start = function() {
var _this = this;
return this.interval_id = window.setInterval((function() {
return _this.tick();
}), 1000);
};
Countdown.prototype.tick = function() {
if (this.difference > 0) {
this.difference--;
return this.callbacks.tick({
seconds: this.pad(this.difference % 60),
minutes: this.pad(Math.floor(this.difference / 60) % 60),
hours: Math.floor(this.difference / 60 / 60) % 24
});
} else {
return this.stop();
}
};
Countdown.prototype.pad = function(number) {
return ("0" + number).slice(-2);
};
Countdown.prototype.complete = function(callback) {
this.stop();
return this.callbacks.complete();
};
Countdown.prototype.stop = function() {
return window.clearInterval(this.interval_id);
};
return Countdown;
})();
$(function() {
var countdown;
return countdown = new Countdown("1351090738", {
tick: function(date) {
$('#countdown .timer .hours').text(date.hours);
$('#countdown .timer .minutes').text(date.minutes);
return $('#countdown .timer .seconds').text(date.seconds);
},
complete: function() {
return typeof console !== "undefined" && console !== null ? typeof console.log === "function" ? console.log('Countdown Complete') : void 0 : void 0;
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.