Zurreal
Zurreal

Reputation: 301

setTimeout with ajax calls

<script type="text/javascript">
   var timeOutID = 0;
   var checkScores = function() {
     $.ajax({
       url: "<?php echo 'http://127.0.0.1/ProgVsProg/main/countScoreCh'?>",
       success:function(response){
       if (response !=' ') {
         $('#scoreCh').html(response);
         clearTimeout(timeOutID);
       } else{
         timeOutID = setTimeout(checkScores, 3000);
       }
     });
   }
   timeOutID = setTimeout(checkScores,1000);
 </script>

I am using setTimeout if there is a change in the database. If there is a change..it will output the change.

My problem is setTimeout will only display the first call.and never checks again if there is another change in the database.

I don't know if setTimeout is the correct way of doing it.

Upvotes: 1

Views: 5715

Answers (2)

Sachin Jain
Sachin Jain

Reputation: 21842

You are making these mistakes

  1. If you want to poll for database changes, don't use setTimeout. Instead use setInterval and clear this interval depending upon your logic like after 50times or something else.
  2. Use a busyFlag because you are making an asynchronous call. (As suggested by @mike)

Try this

var intervalId = null;
var IS_BUSY_FETCHING_UPDATES = false;

var checkScores = function() {
  if (!IS_BUSY_FETCHING_UPDTAES) {
    IS_BUSY_FETCHING_UPDTAES = true;

    $.ajax({
      url: "http://127.0.0.1/ProgVsProg/main/countScoreCh" 
    }).done(function(response){
      if (response) {
        $('#scoreCh').html(response);
      }
    }).fail(function(e) {
      console.error(e);
    }).always(function() {
      IS_BUSY_FETCHING_UPDATES = false; // This will be executed when AJAX gets complete
    });
}

intervalID = setInterval(checkScores,1000);

Upvotes: 1

Michael Schock
Michael Schock

Reputation: 575

Yeah, setTimeout only runs once though. You're looking for setInterval.

<script type="text/javascript">
    var timeOutID = 0;
    var checkScores = function() {
        $.ajax({
            url: "<?php echo 'http://127.0.0.1/ProgVsProg/main/countScoreCh'?>",
            success: function(response) {
                if(response !== '') {
                    $('#scoreCh').html(response);
                }
            }
        });
    };
    timeOutID = setInterval(checkScores, 1000);
</script>

You could also get it working by just getting rid of that else in your success function:

success: function(response) {
    if(response !== '') {
        $('#scoreCh').html(response);
    }
    timeOutID = setTimeout(checkScores, 3000);
},
error: function() {
    timeOutID = setTimeout(checkScores, 3000);
}

Upvotes: 2

Related Questions