0

I have this code to pull out new messages from the database, The issue is: sometimes the ajax request takes too long and it pulls the same message twice.

There is a simple result to set the interval for longer period of time, but even if I'll do really long (about 5 seconds) it may sometimes will have the same issue.

Any ideas how to make sure that it wouldn't happen again?

I think that the best way to do it is to check if getNewMessages is in the middle of the ajax request, and if it is - avoid sending another request.

function getNewMessages() {
    $.ajax({
        url: "@string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"))Chat/GetNewMessages",
        data: {
            LastID: lastId
        },
        type: "POST",
        dataType: "text",
        success: function (text) {
            var arr = jQuery.parseJSON(text);
            var arrLength = arr.length;
            if(arrLength != 0)
                lastId = arr[arrLength - 1]["Id"];

            for (i = 0; i < arrLength; i++) {
                var extraClasses = "";
                if (isUnicode(arr[i]["Message"])) {
                    extraClasses = "rtl";
                }
                if (arr[i]["UserID"] == UserID)
                    $(".messages").append("<div class='ownMessage messageNickname' id='" + arr[i]["Id"] + "'><div class='row nickname'><div class='col-md-12'>" + arr[i]["Nickname"] + "</div></div><div class='row message " + extraClasses + "'><div class='col-md-12'>" + arr[i]["Message"] + "</div></div></div>");
                else
                    $(".messages").append("<div class='messageNickname' id='" + arr[i]["Id"] + "'><div class='row nickname'><div class='col-md-12'>" + arr[i]["Nickname"] + "</div></div><div class='row message " + extraClasses + "'><div class='col-md-12'>" + arr[i]["Message"] + "</div></div></div>");
            }

            if (arrLength > 0) {
                $(".messages").animate({ scrollTop: $(".messages").prop("scrollHeight") }, 2000);
            }
        }
    });
    $(".messageNickname").dblclick(removeMessage);

}

setInterval(getNewMessages, 2000);
Itay
  • 337
  • 5
  • 22
  • 1
    use setTimeout instead of setInterval and see how the things work – Karthick Kumar May 08 '15 at 11:12
  • As @KarthickKumar says, use setTimeout, but use it inside ajax success function – kosmos May 08 '15 at 11:14
  • Polling is an archaic way of checking for messages. Check out web sockets instead. The server can notify the client when a new message comes, so no need for this ajax machinery anymore. See this : http://stackoverflow.com/questions/11077857/what-are-long-polling-websockets-server-sent-events-sse-and-comet – Jeremy Thille May 08 '15 at 11:15

1 Answers1

0

Use a flag variable.

var doingRequest = false;
function getNewMessages() {
    if (!doingRequest) {
        $.ajax({
            beforeSend: function(){
                doingRequest = true;
            },
            complete: function(){
                doingRequest = false;
            }
     });
}
Eduardo Yáñez Parareda
  • 9,126
  • 4
  • 37
  • 50