Question

At the moment I am calling a function on a setInterval basis.

This function makes a XMLHttpRequest to my server to get update info. If there is an update available I update an image (using canvas element).

Is this the optimum way to do this sort of thing?

My code:

Calling code:

    function StartFeedUp() {
        if (tmrStartFeedUp) window.clearInterval(tmrStartFeedUp);
        tmrStartFeedUp = setInterval(GetNextImage, 330);
    }

My called function:

  var isProcess = false;

  function GetNextImage() {
        try {
            if (!isProcess) {
                isProcess = true;
                var urlTS = '/Cloud/isNewFrames.ashx?alias=' + alias + '&version=' + version + '&guidlogon=' + guidlogon;
                var xmlhttp = new XMLHttpRequest();
                xmlhttp.open("GET", urlTS, true);                  
                xmlhttp.timeout = 200;
                xmlhttp.send();
                var nextts = xmlhttp.responseText;
             }
                 isProcess = false;
             }
         catch (err) {
            isProcess = false;
            document.getElementById("divMode2").innerHTML = err;
        } 
    }
Was it helpful?

Solution

Other than repeating the XHR call, you can use HTML5 Web Sockets which allows you to maintain a connection to the server, whereby the server would push data as and when needed. Web Sockets are relatively new and so aren't supported by old browsers.


Your XHR is asyncronous so you should be listening on the onreadystatechange event instead of always expecting the response to be available directly after the send() call:

xmlhttp.open("GET", urlTS, true);                  
xmlhttp.timeout = 200;
xmlhttp.onreadystatechange = function(){
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
        console.log("received " + xmlhttp.responseText);
    }
}
xmlhttp.send();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top