Skip to content

Instantly share code, notes, and snippets.

@halgari
Created August 23, 2013 16:05
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 halgari/6321034 to your computer and use it in GitHub Desktop.
Save halgari/6321034 to your computer and use it in GitHub Desktop.
(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