如何关闭之前的 EventSource

How to close previous EventSource

<button onclick="hoge()">hoge</button>
<script>
function hoge(){
  if(es){
    es.close()
  }
  var es = new EventSource('/hoge')
  es.onmessage = function(e) {
    console.log(e)
  }
}
</script>

我想节省资源,所以点击开始连接EventSource。
每次点击都会启动新的连接,所以我想断开之前的连接。
我试过上面的代码,但没有用。请问我该怎么办。

当您第二次调用该函数时,您没有第一个 EventSource 的实际范围,因此变量 es 对您来说是空的,即使您有一个 [=12] =] 已经实例化。

我不确定你为什么首先关闭并重新创建 EventSource,但这里有一个解决你的确切问题的方法:

试试这个:

<script>
var eventSource;

function hoge(){
    if(eventSource){
        eventSource.close()
    }

    eventSource = new EventSource('/hoge')

    eventSource.onmessage = function(e) {
        console.log(e)
    }
}
</script>

请记住 eventSource 位于全局范围内(换句话说,它直接附加到浏览器上下文中的 window 对象),所以您可能希望将整个代码包装在一个模块中或至少在另一个函数中。简而言之,使用这个:

<script>
(function() {
    var eventSource;

    function hoge(){
        if(eventSource){
            eventSource.close()
        }

        eventSource = new EventSource('/hoge')

        eventSource.onmessage = function(e) {
            console.log(e)
        }
    }
})();
</script>