Click here to Skip to main content
15,893,588 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a function named createNotificTable().This function is using ajax to fetch data.I have to call it in every 5 sec.
"startNotificationTable()" is the function which is called from asp server code and the timer starts.

function startNotificationTable() {

window.setInterval(createNotificTable, 5000);

}

problem is that,createNotificTable is called every 5 sec even if the function is not finished,which creates problem.

So how to do this approach?I don't want to call it exact 5sec interval,just want to call repeatedly but after finishing the execution of this function.

But interval will be better because if the function finished in 2 sec then I don't want to call it immediately as it is accessing database.A interval will be better.

5sec or 10 sec will be better.

Please help.
Posted
Comments
Kuthuparakkal 22-Feb-15 13:38pm    
Set a variable say boolean var FuncRunnig = false
Set the var value appropriately, check this var before calling the function
souvikcode 22-Feb-15 22:39pm    
this can not be done without callback.Because in ajax,the bool value may be changed before server side processing ends. I've tested this type of approach and it is wrong.

1 solution

Done by callback.

C#
function settimer() {
   alert('timer fired');
   setTimeout(function () {
       createNotificTable(function () {
           settimer();
       });
   }, 5000)
}


C#
function createNotificTable(callback) {

    var tbl = $("#gridNotificInbox tbody");
    var empid = $("#hdnempidmaster").val(); //logged in employee
    var maxid = 0;
    if (parseInt($('#gridNotificInbox tbody tr').length) > 0) {
        maxid = Math.max.apply(Math, $("#gridNotificInbox tbody tr td:first-child").map(function () {
            return $(this).text();
        }));
    }
    alert(maxid);

    $.ajax({
        type: "POST",
        url: "notification.aspx/ReturnTableRow",
        data: JSON.stringify({ maxidfetched: maxid, empid: empid }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        beforeSend: function () {

        },
        success: function (response) {
            if (response.d.trim() != "") {
                //tbl.prepend(response.d);
                //alert('hi');
                initializeDatatable(response.d);
            }
            callback();
        },
        failure: function (response) {
            //alert(response.d);
        }

    });
}
 
Share this answer
 
Comments
Santosh K. Tripathi 23-Feb-15 0:50am    
5+

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900