Skip to content

Instantly share code, notes, and snippets.

@oliyh
Last active February 17, 2024 22:34
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oliyh/0c1da9beab43766ae2a6abc9507e732a to your computer and use it in GitHub Desktop.
Save oliyh/0c1da9beab43766ae2a6abc9507e732a to your computer and use it in GitHub Desktop.
Debounce in Clojure on the JVM
(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
@mpereira
Copy link

Works great!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment