Skip to content

Instantly share code, notes, and snippets.

@donpark
Created June 18, 2013 02:34
Show Gist options
  • Save donpark/5802246 to your computer and use it in GitHub Desktop.
Save donpark/5802246 to your computer and use it in GitHub Desktop.
Time and timer related utility functions in Coffee-Script
TimeUtil =
now: Date.now or -> new Date().getTime()
# Returns wrapped function that no-ops if called within specified
# duration in milliseconds of last call.
throttle: (duration, fn) ->
last = 0
->
now = TimeUtil.now()
if now - last < duration
false
else
fn.apply(@, arguments)
last = now
true
# Returns wrapped function that schedules given function to be called
# `duration` milliseconds after *last* call.
#
# NOTE: given function is called at least once, unlike `throttle`.
deferred: (duration, fn) ->
timer = null
->
clearTimeout timer if timer
timer = setTimeout ->
timer = null
fn()
, duration
prettyDate: (time) ->
###
CoffeeScript port of [John Resig's prettyDate](http://ejohn.org/files/pretty.js)
###
secs = (+new Date() - time) / 1000
days = Math.floor(secs / 86400)
return if isNaN(days) or days < 0 or days >= 31
if secs < 60
'just now'
else if secs < 120
'1 minute ago'
else if secs < 3600
"#{Math.floor(secs / 60)} minutes ago"
else if secs < 7200
'1 hour ago'
else if secs < 86400
"#{Math.floor(secs / 3600)} hours ago"
else if days is 1
'yesterday'
else if days < 31
"#{days} days ago"
else if days >= 31
"#{Math.ceil(days / 7)} weeks ago"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment