简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM