delayedServerEvents.sjs (1084B)
1 // this will take strings_to_send.length*500 ms = 5 sec 2 3 var timer = null; 4 var strings_to_send = [ 5 "retry:999999999\ndata\r\n\nda", 6 "ta", 7 ":", 8 "de", 9 "layed1\n\n", 10 "", 11 "", 12 "data:delayed2\n\n", 13 "", 14 "", 15 ]; 16 var resp = null; 17 18 function sendNextString() { 19 if (!strings_to_send.length) { 20 timer.cancel(); 21 resp.finish(); 22 timer = null; 23 resp = null; 24 return; 25 } 26 27 try { 28 resp.write(strings_to_send.shift()); 29 } catch (e) { 30 timer.cancel(); 31 timer = null; 32 resp = null; 33 } 34 } 35 36 function handleRequest(request, response) { 37 var bytes = strings_to_send.reduce((len, s) => len + s.length, 0); 38 39 response.seizePower(); 40 response.write("HTTP/1.1 200 OK\r\n"); 41 response.write(`Content-Length: ${bytes}\r\n`); 42 response.write("Content-Type: text/event-stream; charset=utf-8\r\n"); 43 response.write("Cache-Control: no-cache, must-revalidate\r\n"); 44 response.write("\r\n"); 45 46 resp = response; 47 48 timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); 49 timer.initWithCallback(sendNextString, 500, Ci.nsITimer.TYPE_REPEATING_SLACK); 50 }