Last active
December 16, 2015 08:38
-
-
Save nilsga/5406761 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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