Last active
February 2, 2025 21:28
-
-
Save PEZ/785208524dca981cd6c238959ae74782 to your computer and use it in GitHub Desktop.
ClojureScript Leading Throttle utility
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
(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)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yet another, yes. 😄
Use from some tight loop for whatever.