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);