ClearInterval inside callback in ClojureScript

Basically, I want to implement this piece of code in ClojureScript:

var win = window.open('foo.html', 'windowName');   
var timer = setInterval(function() {   
    if(win.closed) {  
        clearInterval(timer);  
        alert('closed');  
    }  
}, 1000);

I tried this:

(let [popup (.open js/window "foo.html" "windowName")
      interval (.setInterval
                js/window
                (fn []
                  (when (.-closed popup)
                    (do
                      ;; 'interval' is undefined at this point
                      (.clearInterval js/window interval)

                      (.alert js/window 'closed')))
                1000)]
...)

but the CLJS compiler gives me a warning that it is intervalnot defined.

Any ideas?

+4
source share
3 answers

The problem is that you access the local binding intervalin your anonymous function before the binding is defined (the right side needs to be evaluated first before it is bound to the character interval, and until intervalit is defined.

, , :

(let [popup (.open js/window 'foo.html', 'windowName')
      interval (atom nil)]
  (reset! interval (.setInterval
                    js/window
                    (fn []
                      (when (.-closed popup)
                        (do
                          (.clearInterval js/window @interval)
                          (.alert js/window "Closed")))))))

, , .

+4

atom

  • ClojureScript

interval, atom, .
, interval . , :

  • ()

promise . ClojureScript 1.8.34 Clojure promise . - core.async , Clojure ClojureScript - core.async promise-chan. promise-chan

(ns test.core
  (:require-macros [cljs.core.async.macros :refer [go]])
  (:require [cljs.core.async :refer [<! close! promise-chan put!]]))

(let [interval (promise-chan)
      fooWin (.open js/window "./foo.html", "windowName")
      checkOnFooWin 
        (fn []
          (when (.-closed fooWin) ;; when has an implicit do
            (go
              (.clearInterval js/window (<! interval)))
            (.alert js/window "Closed")))]
  (put! interval (.setInterval js/window checkOnFooWin 500))
  (close! interval))

, , atom, ,

  • interval
  • , interval, .
+4

js-:

(let [popup (.open js/window "foo.html" "windowName")]
  (js* "var interval = setInterval(function() {
          if (popup.closed) {
            clearInterval(interval);
            alert('close');
          }
        }, 500);")

    ...)
+1

All Articles