Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I "pause" Server Sent Events?

How I pause a Server Sent Event connection? Is it even possible, or do I have to close the SSE and then reopen it and assign all of the event handlers again?

For example I would like to do (this is all theoretical, I do not know the pause/restart function names):

var source = new EventSource(url);

source.addEventListener("something", somefunction, false);
source.addEventListener("somethingElse", somefunction2, false);

//...some code

source.pause();


//...some code

source.restart();
like image 937
Naftali Avatar asked Oct 29 '25 16:10

Naftali


1 Answers

Yes, that's what technically needs to happen but you can abstract it away. Note: This one only connects after you do .connect()

function EventSource2(url) {
    this.url = url;
    this.es = null;
    this.listeners = {};
}

EventSource2.prototype = {
    constructor: EventSource2,
    
    
    connect: function() {
        this.es = new EventSource(this.url);
        this.bindEvents();
    },
    
    disconnect: function() {
        this.es.close();
        this.es = null;
    },
    
    bindEvents: function() {
        for ( var type in this.listeners ) {
            var evs = this.listeners[type];
            for( var i = 0; i < evs.length; ++i ) {
                this.es.addEventListener( type, evs[i], false );
            }
        }
    },
    
    addEventListener: function( type, fn ) {
        if( !this.listeners[type] ) {
            this.listeners[type] = [];
        }
        
        this.listeners[type].push( fn );
        if( this.es ) {
            this.bindEvents();
        }
    }
}

Usage:

var source = new EventSource2(url);

source.addEventListener("something", somefunction, false);
source.addEventListener("somethingElse", somefunction2, false);

source.connect();

source.disconnect();

source.connect();
like image 99
Esailija Avatar answered Nov 01 '25 12:11

Esailija