-
-
Save neeasade/5592d5260b7537032459e425840e5234 to your computer and use it in GitHub Desktop.
Debounce in Clojure on the JVM
This file contains hidden or 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
(import '[java.util Timer TimerTask]) | |
(defn debounce | |
([f] (debounce f 1000)) | |
([f timeout] | |
(let [timer (Timer.) | |
task (atom nil)] | |
(with-meta | |
(fn [& args] | |
(when-let [t ^TimerTask @task] | |
(.cancel t)) | |
(let [new-task (proxy [TimerTask] [] | |
(run [] | |
(apply f args) | |
(reset! task nil) | |
(.purge timer)))] | |
(reset! task new-task) | |
(.schedule timer new-task timeout))) | |
{:task-atom task})))) | |
;; example usage | |
(def say-hello (debounce #(println "Hello" %1))) | |
(say-hello "is it me you're looking for?") | |
(say-hello "Lionel") | |
;; one second later... | |
;; Hello Lionel |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment