Skip to content

Instantly share code, notes, and snippets.

@daneden
Last active June 20, 2017 19:53
Show Gist options
  • Save daneden/4a3b9278756b6336cefa284ec6408715 to your computer and use it in GitHub Desktop.
Save daneden/4a3b9278756b6336cefa284ec6408715 to your computer and use it in GitHub Desktop.
t = new TextLayer
text: "00:00"
style:
# This style ensures that tabular figures are used, so that all
# digits are the same width
fontFeatureSettings: "'tnum'"
# Get the current time
origin = Date.now()
time = ->
# Get the time at the moment the function is called
now = Date.now()
# Get the difference between the 'origin' time and the time right now,
# then divide by 1000 to turn that from milliseconds to seconds
secs = Math.floor((now - origin) / 1000)
# Now, make our seconds run from 0 to 60 and then reset using modulo
s = secs % 60
# Divide the seconds by 60 to find the number of minutes that have passed
min = Math.floor(secs / 60)
# Add leading zeros if the number of seconds or minutes is less than 10
if s < 10 then s = "0" + s
if min < 10 then min = "0" + min
# Update the text layer
t.text = "#{min}:#{s}"
# setInterval is JS's native `Utils.interval`, that I used just out of habit.
# It takes a function as its first argument, and N number of milliseconds as
# its second, repeating the function every N milliseconds
timer = setInterval(time, 100)
# If you wanted to stop the timer, you could call this function
# e.g. when `secs` in the `time` function is equal to 100.
stopTimer = ->
clearInterval(timer)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment