Last active
December 27, 2015 03:19
-
-
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.
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
;; 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