To close an EventSource connection, you simply call its close()
method.
How to Close an Event Source
The primary method for terminating an active EventSource connection is by invoking the close()
method available on the EventSource
interface. This method is designed to manage the lifecycle of Server-Sent Events (SSE) connections.
Understanding the EventSource.close()
Method
As per the EventSource: close()
method documentation:
- It closes the connection, provided a connection has been established.
- Upon closing, it sets the
EventSource.readyState
attribute to 2 (closed). This allows you to programmatically check the connection's state. - If the connection is already closed, calling
close()
will have no effect; the method does nothing. This makes it safe to callclose()
multiple times without causing errors.
The readyState
Attribute
The readyState
attribute provides insight into the current state of an EventSource
connection. Its values are crucial for understanding what happens when close()
is called:
State | Value | Description |
---|---|---|
CONNECTING |
0 |
The connection has not yet been established, or it was lost and is being re-established. |
OPEN |
1 |
The connection is open and data is flowing. |
CLOSED |
2 |
The connection has been closed or could not be opened. |
When you call eventSource.close()
, the readyState
transitions to 2
, indicating that the connection is no longer active.
Practical Example
Here's a straightforward example demonstrating how to initialize an EventSource
and then close it:
// Create a new EventSource instance
const eventSource = new EventSource('http://example.com/stream');
// Event listener for messages
eventSource.onmessage = function(event) {
console.log('Received message:', event.data);
};
// Event listener for errors
eventSource.onerror = function(error) {
console.error('EventSource failed:', error);
// Optionally close the connection on certain errors
// eventSource.close();
};
// Event listener for open connection
eventSource.onopen = function() {
console.log('EventSource connection opened.');
};
// --- How to close the EventSource ---
// You can close the connection manually, for example, after a certain time,
// after receiving a specific message, or when a user navigates away.
setTimeout(() => {
console.log('Closing EventSource connection...');
eventSource.close();
console.log('EventSource readyState after close:', eventSource.readyState); // Will be 2
}, 10000); // Close after 10 seconds
// Or, for example, on a button click
// document.getElementById('closeButton').addEventListener('click', () => {
// eventSource.close();
// console.log('EventSource closed by user.');
// });
When to Close an EventSource
It's good practice to close an EventSource
connection when it's no longer needed to free up resources and prevent unnecessary network activity. Common scenarios include:
- User Navigation: When a user navigates away from the page that established the
EventSource
connection. - Application State Change: If the application transitions to a state where real-time updates from that specific source are no longer relevant.
- Explicit User Action: Providing a button or mechanism for the user to stop receiving updates.
- Completion of Task: When all necessary data has been received, and no further updates are expected.
- Error Handling: In some error scenarios where automatic reconnection is not desired or feasible, you might choose to explicitly close the connection.
By understanding and utilizing the EventSource.close()
method, you can effectively manage the lifecycle of your Server-Sent Events connections.