1
function chatUpdate() {
    var xmlhttp = new XMLHttpRequest();
    var url = document.URL + '&action=update';

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                var myArr = JSON.parse(xmlhttp.responseText);
                alert(myArr);
        }
    }

    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

setInterval(chatUpdate(), 1000);

This code updates chat every 3 seconds. It alerts myArr correctly (I just alert it for debug purposes), but just for one time – when page loads (but I need it every 3 seconds), although a setInterval is called.

I think the problem is (it must be) that onreadystatechange / readyState are not updated after first request. I tried really hard but I did not succeed in it.

Please, help

MrCode
  • 63,975
  • 10
  • 90
  • 112
tjomamokrenko
  • 159
  • 2
  • 12
  • http://stackoverflow.com/questions/13574882/multiple-xmlhttprequests-every-x-seconds – Avinash Babu Oct 12 '14 at 14:17
  • This question has been asked dozens of times already on SO. See http://stackoverflow.com/questions/3800512/calling-functions-with-settimeout for just one example. I wonder why this is so hard for people to wrap their heads around. The documentation says you pass a function. Is it really so hard to distinguish between a function and a function invocation? –  Oct 12 '14 at 16:08

1 Answers1

2

The issue is with the way you pass the function to setInterval, nothing to do with your XHR call.

Don't use parenthesis when passing a function, just pass the name. By using parenthesis, you are immediately executing the function and passing the return value (undefined in this case).

setInterval(chatUpdate, 1000);
//                    ^ no ()
MrCode
  • 63,975
  • 10
  • 90
  • 112