11

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); 
            } 
        }); 
    }
gideon
  • 19,329
  • 11
  • 72
  • 113
mkizito76
  • 167
  • 1
  • 1
  • 9
  • Have you [checked your debugger](http://blog.niftysnippets.org/2011/03/no-excuse.html) to see whats wrong? The JS seems perfectly fine : http://jsfiddle.net/FgT22/ – gideon Feb 19 '12 at 16:19
  • Yes. It is working fine. It works as expected when there is no data in the database (that is when response is true). When it is false, I want to recheck after x minutes. That is where the issue seems to be. It does not recheck. My ida of clearing the timeout on success is so the next check should not be fired before the previous load is complete – mkizito76 Feb 19 '12 at 16:24
  • This is what I have now and it seems to work. Is this the best way of doing this? By the way, thank you for the help – mkizito76 Feb 19 '12 at 16:40
  • See if my solution works for you. – gideon Feb 19 '12 at 17:01

1 Answers1

27

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);
gideon
  • 19,329
  • 11
  • 72
  • 113
  • Wow, that is awesome! Thank you very much for the help. One more thing, when the load event fires the ajaxFn fines right away. I would like to have a wait (say 10 seconds) before the ajaxFn fires (since the load may take sometime). In other words, I want to wait say 10 seconds before I fire the ajaxFn. Is that possible? – mkizito76 Feb 19 '12 at 17:00
  • @user1219415 You mean you want to wait 10 secs before your FIRST Call? I updated the answer. – gideon Feb 19 '12 at 17:05
  • Would have loved to. I am new here so I cant :-(. – mkizito76 Feb 19 '12 at 17:21
  • :) Upvoting the answer sorta people it was useful, and accepting the answer tells them it works for you. Both these things give me tasty points See [how accepting an answer works](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) – gideon Feb 19 '12 at 17:22
  • @user1219415 aha yea forgot about that! Well anyway Your welcome, Have a great day :) – gideon Feb 19 '12 at 17:24