Skip to content

Instantly share code, notes, and snippets.

@ghostandthemachine
Created December 4, 2017 16:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ghostandthemachine/6e52e433eabd17b45233eb6131cae903 to your computer and use it in GitHub Desktop.
Save ghostandthemachine/6e52e433eabd17b45233eb6131cae903 to your computer and use it in GitHub Desktop.
An example of polling using cljs and setInterval
;; Time between polling requests in milliseconds
(def TIMEOUT 1000)
(defn polling-request
[handler timeout]
;; Will call the handler every timeout interval
(js/setInterval handler timeout))
(polling-request
(fn []
;; do something ever poll timeout like check a db
;; (let [surveys (<! (api/get-all-surveys))]
;; (swap! state* assoc :surveys surveys))
)
;; Time between polling calls
TIMEOUT)
;; I would imagine you could use the polling-request fn in something like
;; `:component-did-mount` of your surveys component to refresh all the surveys
;; every so often.
;; You should also keep track of the id of the setInterval call so you can stop it when you leave that page
;; Something like
(swap! state* assoc :polling-id (polling-request handler timeout))
;; This will store the id of the interval in state*
;; then on `:component-will-unmount` you can/should clear that with
(js/clearInterval (:polling-id @state*))
;;
;; So high level
;; 1. Start a polling function call of whatever (handler) with setInterval
;; 2. Store the id returned from that to kill it later otherwise it will keep polling even when you leave the page
;; 3. Clear the interval when you unmount your page that's polling
@vxe
Copy link

vxe commented Aug 18, 2020

thank you!

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