1

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);
2

3 Answers 3

1

Maybe something like this :

var x = setInterval(function Section(){
  $.getJSON("domain"+ number, addIt);
}, 10000);

if( // something ) {
   clearInterval(x);
 }
Sign up to request clarification or add additional context in comments.

Comments

0

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);
});

9 Comments

hello, thank you for your answer. I am a newbie in AJAX, jQuery and these, what I am trying is to repeat the Section() every x seconds. What is another way to do this, a better way ?
Like I showed you. It will call Section (after a successful call) in 10 seconds but only if no data. If data, it will stop. My method will make sure the loop stops on error too.
I see, this is nice. Can you please tell me why, meaning in a theoretical level why is it bad ?
If your server is slower that the timeout seconds to respond, you will call it again and again while it is still processing
Meaning that if I set the timer to 1 sec, but for a reason it took 2 seconds to respond, that means it will run 2 times. But with your case, it will run upon completion. right?
|
0
var timerId;

function addIt(data) { 
  $(data).insertAfter('#hello');
}

function section() {
  $.getJSON().done(function(data) {
    addIt(data);

    if (timerId) {
      clearInterval(timerId);
    }
  });
}

timerId = setInterval(section, 10000);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.