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);
}
});
}
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)
setTimeoutonly 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/
Your code should look like this :