Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using SetTimeout with Ajax calls

I am trying to use setTimeout to check if data exists in a table:

If the data exists don't fetch data. If the data des not exist fetch the data using load and then do the same thing every x minutes.

Here is what I have so far. For some reason, the setTimeout does not work when it hits the If block.

I am not even sure if this is the best way to do this.

    var sTimeOut = setTimeout(function () {
        $.ajax({
            url: 'CheckIfDataExists/' +
                         new Date().getTime(),
            success: function (response) {
                if (response == 'True') {
                    $('.DataDiv')
                      .load('GetFreshData/' + new Date()
                          .getTime(), { "Id": $("#RowID").val() });
                }
            },
            complete: function () {
                clearTimeout(sTimeOut);
            }
        });
    }, 10000);

Any help will be greatly appreciated.

Updated ...

    setTimeout(function(){checkData()}, 5000);
    function checkData(){
    $.ajax({ 
            url: 'CheckIfDataExists/' + 
                             new Date().getTime(),
            success: function (response) {
                if (response == 'True') {                     
                    $('.DataDiv')
                          .load('GetFreshData/' + new Date()
                              .getTime(), { "Id": $("#RowID").val() });
                } else {
                    $('.OutOfWindow').html('No Data Found');
                    setTimeout(function () { checkData() }, 5000);
                }
            }, 
            complete: function () { 
               // clearTimeout(sTimeOut); 
            } 
        }); 
    }
like image 747
mkizito76 Avatar asked Feb 19 '12 16:02

mkizito76


1 Answers

Something like this should work, the first snippet is localized so I could test run it. I've explained the code and below it is what your code should be

Like you realized (from your update on your post) setTimeout only calls your target function once, so to keep checking you need to call it again if you do a check that fails.

See it on JsFiddle : http://jsfiddle.net/jQxbK/

//we store out timerIdhere
var timeOutId = 0;
//we define our function and STORE it in a var
var ajaxFn = function () {
        $.ajax({
            url: '/echo/html/',
            success: function (response) {
                if (response == 'True') {//YAYA
                    clearTimeout(timeOutId);//stop the timeout
                } else {//Fail check?
                    timeOutId = setTimeout(ajaxFn, 10000);//set the timeout again
                    console.log("call");//check if this is running
                    //you should see this on jsfiddle
                    // since the response there is just an empty string
                }
            }
        });
}
ajaxFn();//we CALL the function we stored 
//or you wanna wait 10 secs before your first call? 
//use THIS line instead
timeOutId = setTimeout(ajaxFn, 10000);

Your code should look like this :

var timeOutId = 0;
var ajaxFn = function () {
        $.ajax({
            url: 'CheckIfDataExists/' + new Date().getTime(),
            success: function (response) {
                if (response == 'True') {
                    $('.DataDiv').
                    load('GetFreshData/' + new Date().
                            getTime(), { "Id": $("#RowID").val() });
                     clearTimeout(timeOutId);
                } else {
                    timeOutId = setTimeout(ajaxFn, 10000);
                    console.log("call");
                }
            }
            });
}
ajaxFn();
//OR use BELOW line to wait 10 secs before first call
timeOutId = setTimeout(ajaxFn, 10000);
like image 66
gideon Avatar answered Oct 12 '22 18:10

gideon