Search code examples
javascriptajaxsettimeout

Ajax polling - Timeout firing with no delay


I use Ajax to poll my IIS/ASP server. I call msgPoll("") once, and then when I trace the polling code I find that msgPoll is invoked repeatedly instead of every 30 seconds. What am I doing wrong?

var msgTimOut;
function msgPoll(text) {
    var msgData = {};
    msgData.UID = $("#hidUID").val();
    msgData.data = text;
    $.ajax({
        type: "POST",
        url: "WSWebJudge.asmx/MsgPoll",
        cache: false,
        data: JSON.stringify(msgData),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            resp=JSON.parse(data.d);
            if (resp.status == 1) setMsg(resp.msg);
            if (msgTimOut) clearTimeout(msgTimOut);
            msgTimOut = setTimeout(msgPoll(""), 3000);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert("Messaging - textStatus: " + textStatus + " errorThrown: " + errorThrown);
        }
    });
}       

Solution

  • setTimeout(function(){msgPoll("")}, 30000)

    1. You have 3 seconds instead of 30 seconds
    2. Call it within a function block - see https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout for more discussion.