Вопрос

How can I process an infinite sequence in ClojureScript, doing DOM manipulations per element, and then waiting some time before continuing (for example, if I wanted to have a div on a page that was showing a number that incremented once per second)?

Using the dommy library for DOM interaction, here's a (non-working) code example:

(def container (sel1 :#container))

(defn integers [] (iterate inc 0))

(js/setInterval
  (fn []
    (dommy/set-text! container (nth (integers) i)) ; whence i?
    )
  1000)

Obviously indexing into this sequence is not a long-term solution.

Это было полезно?

Решение

This, for example, works:

(def container (sel1 :#container))

(def integers (iterate inc 0))

(defn set-int! [[x & rs :as nums]]
  (when nums
    (js/setTimeout
      #(do (dommy/set-text! container i)
           (set-int! rs))
      1000)))

(set-int! integers)

Anyway, what are you trying to accomplish? It is a pretty weird way of making a counter, and you are going to be blowing memory with the infinite sequence.

With an atom it would be much cleaner and efficient:

(def container (sel1 :#container))
(def set-int! (partial dommy/set-text! container))

(def counter (atom 0))

(js/setInterval
  #(do (swap! counter inc)
       (set-int! @counter))
  1000)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top