Ours Ours - 1 year ago 57
jQuery Question

HTML5/Javascript SSE limit number of calls

I'm fairly new to ServerSend Events using js and HTML5. I have a basic set up with my page calling an API, the API execute a command line, and I'm trying to display the result of this call in realtime (the api is calling a script on the server and i'm serving the console output).

My problem is that if the page stays open, the API keeps on getting called. I would like to stop this behavior and having the API called only once. I tried using a boolean to define the event source only once but with no luck.

Here is my js code:

function liveExec($scenarioId){
var $run = true;
if ($run)
var source = new EventSource('/run/'+$scenarioId+'/1');
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
$run= false;

The function is called with a button click.
Here is my access Log: - - [28/Oct/2016:11:09:06 +0200] "GET /run/1/1 HTTP/1.1" 200 2318 - - [28/Oct/2016:11:09:31 +0200] "GET /run/1/1 HTTP/1.1" 200 2318 - - [28/Oct/2016:11:09:56 +0200] "GET /run/1/1 HTTP/1.1" 200 2318 - - [28/Oct/2016:11:10:21 +0200] "GET /run/1/1 HTTP/1.1" 200 2318 - - [28/Oct/2016:11:10:47 +0200] "GET /run/1/1 HTTP/1.1" 200 2317

Visibly the function is called every 25 seconds for some reason.

Any help would be appreciated! Thanks!

Answer Source

What about closing the connection by means of source.close(); after running it for the first time?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download