Skip to content

Instantly share code, notes, and snippets.

@janmartenjongerius
Created October 5, 2015 21:30
Show Gist options
  • Save janmartenjongerius/01e7222bd2348df5621e to your computer and use it in GitHub Desktop.
Save janmartenjongerius/01e7222bd2348df5621e to your computer and use it in GitHub Desktop.
"use strict";
; var Timer = (function () {
var defineIntervalProperties = function (target, starter, ender) {
Object.defineProperties(
target,
{
'start': {
'get': starter
},
'end': {
'get': ender
},
'milliseconds': {
'get': function () {
return this.end - this.start;
}
},
'seconds': {
'get': function () {
return this.milliseconds / 1e3;
}
},
'minutes': {
'get': function () {
return this.seconds / 60;
}
},
'hours': {
'get': function () {
return this.minutes / 60;
}
},
'days': {
'get': function () {
return this.hours / 24;
}
}
}
);
// Make the object immutable.
Object.seal(target);
};
var T = function (start) {
if (!Number.isInteger(start)) {
start = +new Date;
}
defineIntervalProperties(
this,
function () {
return start;
},
function () {
return +new Date;
}
);
};
T.prototype.diff = function (timer) {
if (!(timer instanceof T)) {
throw new Error('Invalid timer supplied');
}
return new this.Interval(this.start, timer.start);
};
T.prototype.Interval = function (start, end) {
if (!Number.isInteger(start)) {
start = +new Date;
}
if (!Number.isInteger(end)) {
end = +new Date;
}
defineIntervalProperties(
this,
function () {
return start;
},
function () {
return end;
}
);
};
T.Countdown = function (d) {
if (!(d instanceof Date)) {
throw new Error('Invalid date supplied');
}
var timer = new T, end = +d;
defineIntervalProperties(
this,
function () {
return timer.end;
},
function () {
return end;
}
);
};
return T;
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment