Skip to content

Instantly share code, notes, and snippets.

@yuriuliam
Created February 24, 2022 03:55
Show Gist options
  • Save yuriuliam/6786c4d96090a6223730132b57163415 to your computer and use it in GitHub Desktop.
Save yuriuliam/6786c4d96090a6223730132b57163415 to your computer and use it in GitHub Desktop.
/**
* Creates a timer
* @param {number} secondsAmount Amount of time in seconds
* @param {number} minutesAmount Amount of time in minutes
* @param {number} hoursAmount Amount of time in hours
* @param {number} daysAmount Amount of time in days
* @returns an object representing the timer.
*/
function createTimer(
secondsAmount = 0,
minutesAmount = 0,
hoursAmount = 0,
daysAmount = 0,
) {
if (daysAmount <= 0 && hoursAmount <= 0 && minutesAmount <= 0 && secondsAmount <= 0) {
throw new RangeError('cannot define a timer without a proper time range')
}
if (daysAmount === 0 && hoursAmount === 0 && minutesAmount === 0 && secondsAmount === 0) {
throw new Error('cannot define a timer without a proper start time')
}
let timerValue = 0
timerValue += secondsAmount
timerValue += (minutesAmount * 60)
timerValue += (hoursAmount * 60 * 60)
timerValue += (daysAmount * 24 * 60 * 60)
const startTime = timerValue
let timerInterval = setInterval(timeTick, 1000)
const timerObj = {
value: formatTimer(),
continueTimer,
pauseTimer
}
/**
* Returns the formatted timer in `xx:xx:xx:xx`.
* the format can be different based on the initial values.
* @returns {string}
*/
function formatTimer() {
const days = Math.floor((timerValue / 24 / 60 / 60)).toString().padStart(2, '0')
const hours = Math.floor((timerValue / 60 / 60) % 24).toString().padStart(2, '0')
const minutes = Math.floor((timerValue / 60) % 60).toString().padStart(2, '0')
const seconds = Math.floor(timerValue % 60).toString().padStart(2, '0')
const timerArray = []
if (startTime >= 86400) timerArray.push(days)
if (startTime >= 3600) timerArray.push(hours)
if (startTime >= 60) timerArray.push(minutes)
timerArray.push(seconds)
return timerArray.join(':')
}
/** triggers the timer to continue */
function continueTimer() {
if (timerInterval !== -1) return
timerInterval = setInterval(timeTick, 1000)
}
/** triggers the timer to pause */
function pauseTimer() {
if (timerInterval === -1) return
clearInterval(timerInterval)
timerInterval = -1
}
function timeTick() {
if (timerValue === 0) return
timerValue -= 1
timerObj.value = formatTimer()
}
return timerObj
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment