Skip to content

Instantly share code, notes, and snippets.

@PEZ
Last active February 2, 2025 21:28
Show Gist options
  • Save PEZ/785208524dca981cd6c238959ae74782 to your computer and use it in GitHub Desktop.
Save PEZ/785208524dca981cd6c238959ae74782 to your computer and use it in GitHub Desktop.
ClojureScript Leading Throttle utility
(ns pez.throttle)
(defonce !throttles (atom {}))
(defn dispatch! [{::keys [id timeout thunk]}]
(let [maybe-schedule (fn [current-throttles]
(if (contains? current-throttles id)
current-throttles
(assoc current-throttles id
{:timeout
(delay
(js/setTimeout
(fn []
(swap! !throttles dissoc id))
timeout))})))
[previous-throttles new-throttles] (swap-vals! !throttles maybe-schedule)]
(when-not (contains? previous-throttles id)
(-> new-throttles (get id) :timeout deref)
(thunk))))
@PEZ
Copy link
Author

PEZ commented Jan 31, 2025

Yet another, yes. 😄

Use from some tight loop for whatever.

(throttle/dispatch! {::throttle/id ::boom
                     ::throttle/thunk #(js/console.log "BOOM!")
                     ::throttle/timeout 300})

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