我是javascript中EventSource功能的新手。據我了解,事件源使用流內容呼叫 api 并自動獲取資料更新,而無需進行任何進一步呼叫。但我打算盡可能在 10 秒后停止監聽來自 EventSource 的回應。例如,在下面的 URL 中,我們可以找到 EventSource 示例,我希望它在 10 秒后停止偵聽/獲取。
https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_sse
uj5u.com熱心網友回復:
您可以使用方法并以如下EventSource.close()方式呼叫它(改編自鏈接的 W3Schools 代碼):setTimeout()
if(typeof(EventSource) !== "undefined") {
const source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
console.log(event.data);
};
setTimeout(() => {
source.close();
console.log("connection closed");
}, 10000)
} else {
console.log("Sorry, your browser does not support server-sent events...");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/478470.html
