Skip to content

Instantly share code, notes, and snippets.

@a-x-
Last active February 26, 2018 13:46
Show Gist options
  • Save a-x-/9cdd80e2639ba15f148c9fb05d49bca8 to your computer and use it in GitHub Desktop.
Save a-x-/9cdd80e2639ba15f148c9fb05d49bca8 to your computer and use it in GitHub Desktop.
simple delayed timer with onExpire callback
const SEC = 1000
const MIN = SEC * 60
/** @param time, Δ ms */
function getMinSec(time) {
return {
sec: Math.floor((time % MIN) / SEC),
min: Math.floor(time / MIN)
}
}
/** @param time, Δ ms */
function formatTime(time) {
var time = getMinSec(time)
return pad2(time.min) + ':' + pad2(time.sec)
}
function pad2 (number) {
return number > 9 ? number : ('0' + number)
}
/**
* @param interval, Δ ms
* @param delayShow, Δ ms
* @param onExpire — callback
**/
function startTimer(interval, delayShow, onExpire) {
var initialTime = new Date().valueOf()
/** always positive */
function calcElapsed() {
var currentTime = new Date().valueOf()
var elapsed = interval - (currentTime - initialTime)
return elapsed > 0 ? elapsed : 0
}
function handleExpire() {
hide()
onExpire()
}
function tick() {
var elapsed = calcElapsed()
if (!elapsed) handleExpire()
return renderTimer({ 'time-remained': formatTime(elapsed) })
}
function start() {
tickId = window.setInterval(tick, SEC / 2)
return showTimer()
}
function hide() {
if (tickId) window.clearInterval(tickId)
tickId = null
return hideTimer()
}
function renderTimer(data) {
// ...
}
function showTimer() {
// ...
}
function hideTimer() {
// ...
}
return window.setTimeout(start, delayShow)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment