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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With