Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clearInterval inside callback in ClojureScript

Basically, what I want is 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 CLJS compiler gives me a warning that interval is not defined.

Any ideas?

like image 410
OlegTheCat Avatar asked Dec 25 '22 07:12

OlegTheCat


1 Answers

The issue is that you access interval local binding in your anonymous function before that binding has been defined (right hand side has to be evaluated first before it gets bound to interval symbol and until then interval is not defined.

You might workaround it by defining an atom storing your interval and access it from your callback function:

(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")))))))

I am not sure if there is a more elegant way to achieve it using your approach with an interval callback.

like image 182
Piotrek Bzdyl Avatar answered Jan 02 '23 19:01

Piotrek Bzdyl