Reputation: 8836
The Section()
is responsible to look on database and get any HTML code if some things are matched. If nothing matched, there is no callback (but I can callback an empty thing).
Then it calls addIt()
and display the HTML. Works fine.
My question is when there is some HTML to get from database, to stop the timer? Because for now it adds HTML every 10 seconds.
function addIt(data) { $(data).insertAfter('#hello'); }
setInterval(function Section(){
$.getJSON("domain"+ number, addIt);
}, 10000);
Upvotes: 1
Views: 133
Reputation: 177786
I would never call AJAX in an interval. Instead use the callback to call again
function Section(){
$.getJSON("domain"+number,addIt);
}
function addIt(data) {
if (data) $(data).insertAfter('#hello');
else setTimeout(Section,10000); // call again in 10 seconds unless data was returned
}
Section(); // first call
If the call results in an ERROR when not returning data, try this:
$.getJSON("domain"+number, function(data) {
if (data) $(data).insertAfter('#hello');
})
.fail(function() {
setTimeout(Section,10000);
});
Upvotes: 0
Reputation: 3464
var timerId;
function addIt(data) {
$(data).insertAfter('#hello');
}
function section() {
$.getJSON().done(function(data) {
addIt(data);
if (timerId) {
clearInterval(timerId);
}
});
}
timerId = setInterval(section, 10000);
Upvotes: 0
Reputation: 2673
Maybe something like this :
var x = setInterval(function Section(){
$.getJSON("domain"+ number, addIt);
}, 10000);
if( // something ) {
clearInterval(x);
}
Upvotes: 1