ale
ale

Reputation: 11820

Running code only every n seconds (controlling the frequency of AJAX requests)

I have some code that is executed on the keyup event:

$('#some-text-box').keyup(function() {
   var $text = $(this).text();
   // do some ajax stuff using $text
});

How do I change the above to only do an AJAX request every n milliseconds?

Thank you :).

Upvotes: 3

Views: 636

Answers (3)

dku.rajkumar
dku.rajkumar

Reputation: 18568

var flag = true;
$('#some-text-box').keyup(function() {
   var $text = $(this).text();
   if(flag){          
      flag = false;
      $.ajax({
         // other parameter
         success : function(){                  
             setTimeout(function(){
                 flag = true;
                }, 5000);
         }
      });
   }
});

Upvotes: 3

musefan
musefan

Reputation: 48415

this should work for you...

var canAjaxFlag = true;

$('#some-text-box').keyup(function() {
   var $text = $(this).text();
   if(canAjaxFlag){
      canAjaxFlag = false;//set this as quickly as possible
      // do some ajax stuff using $text
      setTimeout(function(){
         canAjaxFlag = true;
      }, 1000);
   }
});

You will see that the interval has been set to 1000 milliseconds, you can change this to suit your needs

IMPORTANT: Use setTimeout not setInterval, you don't want it to keep running after the falg is set back to true - thanks to @amnotiam for the heads up

Here is a working example

Upvotes: 3

Sam Dufel
Sam Dufel

Reputation: 17598

Inside your document ready function -

var params = null;
var frequency = 300;

$('#some-text-box').keyup(function() {
   var $text = $(this).text();
   params = {
     //stuff we'd like to send to the server
   }
});

setInterval(function() {
  if (params !== null) {
     $.ajax({
         //Send in params here
     });
     params = null;
  }
}, frequency);

Upvotes: 0

Related Questions