Created
December 4, 2017 16:07
-
-
Save ghostandthemachine/6e52e433eabd17b45233eb6131cae903 to your computer and use it in GitHub Desktop.
An example of polling using cljs and setInterval
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
;; 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thank you!