1

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;
        } 
    }
Andrew Simpson
  • 6,883
  • 11
  • 79
  • 179

1 Answers1

2

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();
MrCode
  • 63,975
  • 10
  • 90
  • 112
  • Hi, thanks for your comment. Are you suggesting (apart from using web sockets) that I am doing this the best way possible? Also, when I looked at using web sockets it seemed to imply that it only really works as it should in Windows 8. Thanks for correction BTW. I have implemented it. ta – Andrew Simpson Apr 16 '14 at 14:37
  • WebSockets should work fine outside of Windows 8, I've not heard of that problem before. Be sure to check the W3 or MDN docs for reliable info. WS is definitely what I would do in this case because the repeating XHR is doing 3 requests per second so is not ideal. I believe you can have the server hold the connection open and keep sending data via the XHR where it effectively never completes but doing this you'd be reinventing WS. – MrCode Apr 16 '14 at 14:58