0

I created a code that will run every 3 seconds, and do a $.get query. But everytime the first $.get becomes successful, the loop stops and won't continue at all.

Here is the code I wrote:

var gcount = 0;
setInterval(askData(), 3000);
function askData(){
$.get( "parse.php").done(function( data ) {
  //e.preventDefault();
  var arr = jQuery.parseJSON(data);
  var resp = arr.resp;
  var url = arr.url;
  var count = arr.count;
  var max = arr.max;
  if (gcount != count){
    alert (gcount);
    alert(count);
    gcount = count;
    $("#count").text(count);
    $("#max").text(max).queue(remSlide(url));
  }
  if (resp == 1){
   $("#resp").text('Connected');
  }else{
   $("#resp").text('Error');
  }
});
}
function remSlide(url){
    $("#slide").fadeOut(800, function(){
    $(this).remove().queue(addSlide(url));
    });
}
function addSlide(url){
    $("#content").append('<div id="slide" style="background:url('+url+');"></div>').delay(500);
    $("#slide").hide();
    $("#slide").fadeIn(1000);
    $("html, body").animate({ scrollTop: 0 }, "slow");
}
weyhei
  • 479
  • 2
  • 7
  • 26
  • 1
    Change second line into `setInterval(askData, 3000);` – Regent Sep 18 '14 at 05:36
  • ```setInterval(askData(), 3000);``` should be ```setInterval(askData, 3000);``` – sahbeewah Sep 18 '14 at 05:36
  • 2
    you need to pass function reference to `setInterval()` like `setInterval(askData, 3000);` - in your case you are invoking the `askData()` function and is passing the value returned from it `undefined` as the `setTimeout()` callback – Arun P Johny Sep 18 '14 at 05:38
  • Note the duplicate title would fit absolutely perfectly if it was amended as so: "Why is my function call that should be scheduled by [setInterval] *executed immediately* [and *not again*]?" – user2864740 Sep 18 '14 at 05:39

0 Answers0