Last active
February 17, 2024 22:34
-
-
Save oliyh/0c1da9beab43766ae2a6abc9507e732a to your computer and use it in GitHub Desktop.
Debounce in Clojure on the JVM
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
(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
Works great!