 ;; In a perpetual loop, read events from "event-chan", and call the right handler.
 ;;
 ;; Because handlers occupy the CPU, before each event is handled, hand
-;; back control to the browser, via a (<! (timeout 0)) call.
+;; back control to the browser, via a (<! (yield)) call.
 ;;
 ;; In some cases, we need to pause for an entire animationFrame, to ensure that
 ;; the DOM is fully flushed, before then calling a handler known to hog the CPU

  (:require [reagent.core        :refer [flush]]
            [re-frame.handlers   :refer [handle]]
            [re-frame.utils      :refer [warn error]]
            [cljs.core.async     :refer [chan put! <! timeout]]))

;; -- The Event Conveyor Belt  --------------------------------------------------------------------
;;

;;   (dispatch ^:flush-dom  [:event-id other params])
;;

(defn yield
  "Yields control to the browser. Faster than (timeout 0).
  See http://dev.clojure.org/jira/browse/ASYNC-137"
  []
  (let [ch (chan)]
    (goog.async.nextTick #(close! ch))
    ch))


(defn router-loop
  []
  (go-loop []
           (let [event-v  (<! event-chan)                   ;; wait for an event
                 _        (if (:flush-dom (meta event-v))   ;; check the event for metadata
                            (do (flush) (<! (timeout 20)))  ;; wait just over one annimation frame (16ms), to rensure all pending GUI work is flushed to the DOM.
                            (<! (yield)))]              ;; just in case we are handling one dispatch after an other, give the browser back control to do its stuff
             (try
               (handle event-v)

