Fix bug in debounce

This commit is contained in:
arne 2025-11-19 22:14:32 +01:00
commit b0b4b01e37

View file

@ -267,18 +267,21 @@
;;; views ;;; views
(defn debounce [ms f] (defn debounce
"Wraps `f` so it's called at most once every `ms` milliseconds. Will schedule
the last call to `f` so that it's called after the delay has passed, and will
always prefer to call the most recent call to `f` as close to the delay
as possible."
[ms f]
(let [prev (volatile! (js/Date.now)) (let [prev (volatile! (js/Date.now))
trail (volatile! (js/setTimeout (fn dummy []) ms))] scheduled (volatile! (js/setTimeout (fn dummy []) ms))]
(fn debounced-fn [& args] (fn debounced-fn [& args]
(let [now (js/Date.now)] (let [now (js/Date.now)]
(if (> (- now @prev) ms) (js/clearTimeout @scheduled)
(do (vreset! prev now) (vreset! scheduled (js/setTimeout (fn []
(apply f args))
(do (js/clearTimeout @trail)
(vreset! trail (js/setTimeout (fn []
(vreset! prev (js/Date.now)) (vreset! prev (js/Date.now))
(apply f args)))))))))) (apply f args))
(max 0 (- ms (- now @prev)))))))))
(defn search [] (defn search []
[:input {:placeholder "Start typing to search…" [:input {:placeholder "Start typing to search…"