Created
August 19, 2014 13:18
-
-
Save daveliepmann/5297906c164129643f5e to your computer and use it in GitHub Desktop.
ClojureScript stopwatch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns stopwatch) | |
(defn seconds-to-time | |
[secs] | |
(let [d (js/Date. (* secs 1000))] | |
{:hours (.getUTCHours d) | |
:minutes (.getUTCMinutes d) | |
:seconds (.getUTCSeconds d)})) | |
(defn display-time | |
"Pretty-prints minutes:seconds, given time map of the form {:hours x :seconds y}." | |
[tm] | |
(let [pad (fn [n] | |
(if (< n 10) | |
(str "0" n) | |
n)) | |
mm (pad (:minutes tm)) | |
ss (pad (:seconds tm))] | |
;; (str mm ":" ss) <-- if you were to actually use this to update the DOM | |
(.log js/console (str mm ":" ss)))) | |
(def clock (atom 0)) | |
(def start-time (atom 0)) | |
(def time-fn (atom inc)) ;; included so we can swap it out for countdowns | |
(defn keep-time [func] | |
(display-time (seconds-to-time @clock)) | |
(swap! clock func)) | |
(defonce interval (atom 0)) | |
(defn pause [] | |
(js/clearInterval @interval)) | |
(defn start [] | |
(reset! interval (js/setInterval #(keep-time @time-fn) 1000))) | |
(defn reset [] | |
(js/clearInterval @interval) | |
(reset! clock @start-time)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment