Created
August 23, 2013 16:05
-
-
Save halgari/6321034 to your computer and use it in GitHub Desktop.
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
(ns cljs.core.async.impl.dispatch | |
(:require [cljs.core.async.impl.buffers :as buffers])) | |
(def message-channel nil) | |
(def tasks (buffers/ring-buffer 32)) | |
(def ^:boolean running? false) | |
(def ^:boolean queued? false) | |
(def TASK_BATCH_SIZE 1024) | |
(defn process-messages [] | |
(set! running? true) | |
(set! queued? false) | |
(loop [count 0] | |
(when-let [m (.pop tasks)] | |
(m) | |
(when (< count TASK_BATCH_SIZE) | |
(recur (inc count))))) | |
(set! running? false)) | |
(when (exists? js/MessageChannel) | |
(set! message-channel (js/MessageChannel.)) | |
(set! (.. message-channel -port1 -onmessage) | |
(fn [msg] | |
(process-messages)))) | |
(defn queue-dispatcher [] | |
(when-not (and queued? | |
running?) | |
(set! queued? true) | |
(cond | |
(exists? js/MessageChannel) (.postMessage (.-port2 message-channel) 0) | |
(exists? js/setImmediate) (js/setImmediate process-messages) | |
:else (js/setTimeout process-messages 0)))) | |
(defn run [f] | |
(.unbounded-unshift tasks f) | |
(queue-dispatcher)) | |
(defn queue-delay [f delay] | |
(js/setTimeout f delay)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment