Skip to content

Instantly share code, notes, and snippets.

@michaelsbradleyjr
Last active December 27, 2015 03:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaelsbradleyjr/7258997 to your computer and use it in GitHub Desktop.
Save michaelsbradleyjr/7258997 to your computer and use it in GitHub Desktop.
A macro for "deferring" a ClojureScript function call within a core.async `go` block. Could be used, for example, in conjunction with "subroutines" in a `go-loop` so that those function calls yield back a little time to the CPU before they are executed, thus allowing for a little breathing room between or within expensive subroutines.
;; use only inside a go block; body should be of the form (fn-name arg1 arg2 ...)
;; fn-name must be apply-able, e.g. it cannot be a macro; assumes `setImmediate`
;; is available in the browser's global scope
(defmacro defer [body]
`(let [yield# (cljs.core.async/chan)]
(js/setImmediate #(cljs.core.async/put! yield# (list ~@(rest body))))
(apply ~(first body) (cljs.core.async/<! yield#))))
;; sample usage :: will log `6` to the console
;; -----------------------------------------------
;; (go (.log js/console (+ 1 (defer (+ 2 3)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment