-
-
Save anonymous/ab675299b50d5f34adc1 to your computer and use it in GitHub Desktop.
Register-able Clock Object in JS
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
// usage example: where 1 real second = 1 game hour | |
// says "did it" every game hour, i.e. every real second | |
/* | |
var clock = new Clock(); | |
clock.onHourPass({ | |
name: 'dothat', | |
fn: function(args){ | |
console.log('did it'); | |
} | |
}); | |
clock.start(); | |
*/ | |
function Clock(args) { | |
var self = this; | |
args = args || {}; | |
self.realSecondsInGameHour = args.gameHour || 1; | |
self.gameMinutesInGameHour = args.gameMinutesInGameHour || 4; | |
self.gameHoursInGameDay = args.gameHoursInGameDay || 15; | |
self.gameDay = self.realSecondsInGameHour * self.gameHoursInGameDay; | |
self.hourlyEvents = {}; | |
self.dailyEvents = {}; | |
self.interval; | |
self._hour; | |
this.onHourPass = function(args) { | |
self.hourlyEvents[args.name] = args.fn; | |
} | |
this.onDayPass = function(args) { | |
self.dailyEvents[args.name] = args.fn; | |
} | |
this._triggerHourlyEvents = function(){ | |
var events = Object.keys(self.hourlyEvents); | |
events.forEach(function(e){ | |
self.hourlyEvents[e](self); | |
}); | |
} | |
this._triggerDailyEvents = function(){ | |
var events = Object.keys(self.dailyEvents); | |
events.forEach(function(e){ | |
self.dailyEvents[e](self); | |
}); | |
} | |
this.start = function() { | |
self._hour = 0; | |
self._minute = 0; | |
console.log('clock interval start'); | |
self.interval = window.setInterval(function(){ | |
self._minute++; | |
self._hour = self._minute / self.gameMinutesInGameHour; | |
if(self._minute % self.gameMinutesInGameHour == 0) { | |
self._triggerHourlyEvents(); | |
} | |
if(self._hour == self.gameHoursInGameDay) { | |
self._triggerDailyEvents(); | |
self.end(); | |
} | |
}, (self.realSecondsInGameHour/self.gameMinutesInGameHour) * 1000); | |
} | |
this.end = function() { | |
console.log('clock day ended in ' + self._hour + ' hours'); | |
window.clearInterval(self.interval); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment