Skip to content

Instantly share code, notes, and snippets.

@muratgozel
Created November 6, 2019 20:29
Show Gist options
  • Save muratgozel/e0779fa0edb8a2499b6755a28ac2a025 to your computer and use it in GitHub Desktop.
Save muratgozel/e0779fa0edb8a2499b6755a28ac2a025 to your computer and use it in GitHub Desktop.
function configureTimeAgo(element) {
const elementID = element.getAttribute('id')
let updater = setInterval(function() {
const elementStillExistInDOM = document.getElementById(elementID)
if (!elementStillExistInDOM) {
clearInterval(updater)
return;
}
const seconds = (Date.now() - parseFloat(element.dataset.timestamp)) / 1000
let expression = null
if (seconds < 60) expression = 'just now'
else if (seconds >= 60 && seconds < 3600) {
const mins = Math.floor(seconds / 60)
expression = mins + ' minute' + mins > 1 ? 's' : '' + ' ago'
}
else if (seconds >= 3600 && seconds < 86400) {
const hours = Math.floor(seconds / 3600)
expression = hours + ' hour' + hours > 1 ? 's' : '' + ' ago'
}
else {
const days = Math.floor(seconds / 86400)
expression = days + ' day' + days > 1 's' : '' + ' ago'
}
element.innerHTML = expression
}, 5000)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment