Skip to content

Instantly share code, notes, and snippets.

@nilsga
Last active December 16, 2015 08:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nilsga/5406761 to your computer and use it in GitHub Desktop.
Save nilsga/5406761 to your computer and use it in GitHub Desktop.
function MatchClock(match, callback) {
this.currentHalf = match.currentHalf || 0;
this.currentHalfOffset = match.currentHalfOffset || 0;
this.startTime = new Date(match.startTime);
this.paused = match.paused;
this.clockDiff = new Date().getTime() - new Date(match.serverTime).getTime();
this.callback = callback;
if(typeof this.paused !== "undefined" && !this.paused) {
this.start(this.callback);
}
match.on('change', function(data) {
console.log("Received event: %j, %j", data, this);
if(data.type === EventType.PAUSE || data.type === EventType.MATCH_END) {
console.log("Received pause or half time event. Stopping");
this.stop();
}
else if(data.type === EventType.HALF_START || data.type === EventType.MATCH_START) {
if(data.type === EventType.MATCH_START) {
this.startTime = new Date(data.matchTime.start);
}
this.currentHalf = data.half;
this.currentHalfOffset = data.offset;
this.start(this.callback);
}
}.bind(this));
}
MatchClock.prototype.start = function(cb) {
this.paused = false;
this.interval = setInterval(function() {
this.computeTime();
cb();
}.bind(this), 1000);
console.log("Interval: %j %j", this, this.interval);
};
MatchClock.prototype.stop = function() {
console.log("Attempting to clear interval: %j", this.interval);
this.paused = true;
clearInterval(this.interval);
};
MatchClock.prototype.computeTime = function() {
var adjustedOffset = (new Date().getTime() - this.clockDiff - this.startTime.getTime()) / 1000;
var halfOffset = adjustedOffset - this.currentHalfOffset;
var base = (this.currentHalf - 1) * (this.halfLength || 45) * 60;
var matchOffset = base + halfOffset;
this.min = Math.floor(matchOffset / 60);
this.sec = Math.round(matchOffset - this.min * 60);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment