I created a simple clock & calendar system using a fictional system: everything from the number of seconds in a minute, down to the number of months in a year could be different from our accepted norms (i.e. the Gregorian Calendar). (For the purposes of testing the system I have declared that there are 2 seconds in a minute and the calendar uses Elder Scrolls naming for months and days of the week.)
Eventually I'd like to incorporate this into a game, so the function setInterval that currently increments the seconds is a simple stand-in for a more sophisticated kind of game loop.
The full code (with visual output) can be found at this JSFiddle.
I'm particularly interested in feedback on this method, which handles the incrementation of time:
function incrementOneSecond() { secondIndex++; currentSecond = secondIndex; if (secondIndex > secondsPerMinute) { secondIndex = 0; minuteIndex++; currentMinute = twoDigitFormat(minuteIndex); if(minuteIndex > minutesPerHour) { minuteIndex = 0; hourIndex++; currentHour = twoDigitFormat(hourIndex); if (hourIndex > hoursPerDay) { hourIndex = 0; dayIndex++; currentDay = weekdays[dayIndex]; if (dayIndex >= weekdays.length) { dayIndex = 0; dateNumberIndex++; currentDateNumber = dateNumberIndex; if (dateNumberIndex > monthMaxDays) { dateNumberIndex = 1; monthIndex++; currentMonth = months[monthIndex]; if (monthIndex >= months.length) { monthIndex = 0; yearIndex++; currentYear = yearIndex; } } } } } } updateTime(currentMinute, currentHour, currentDay, currentMonth, currentDateNumber, currentYear); } There's a lot of repetition, so it feels like I should be able to DRY it up, but because each if statement differs slightly, I haven't been able to come up with a way of rewriting the method in a way that is more efficient but also still readable.
Other methods used:
function twoDigitFormat(input) { formatted = ("0" + input).slice(-2) return formatted; } function updateTime(currentMinute, currentHour, currentDay, currentMonth, currentDateNumber, currentYear) { timeDisplay.innerHTML = currentHour + ':' + currentMinute; dateDisplay.innerHTML = currentDay + '<br/>' + currentMonth + ' ' + currentDateNumber + ', ' + currentYear; }