Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery event only every time interval

$(document).ready(function() {

    $('#domain').change(function() {

        //

    });

});

The code inside the change function will basically send ajax request to run a PHP script. The #domain is a text input field. So basically what I want to do is to send ajax requests as user types in some text inside the text field (for example search suggestions).

However, I would like to set a time interval in order to lessen the load of PHP server. Because if jQuery sends AJAX request every time user adds another letter to the text field it would consume lots of bandwidth.

So I would like to set let's say 2 seconds as an interval. The AJAX request will be fired every time the user types a letter but with maximum frequency of 2 seconds.

How can I do that?

like image 768
Richard Knop Avatar asked Nov 30 '22 06:11

Richard Knop


2 Answers

$(function() {
  var timer = 0;
  $("#domain").change(function() {
    clearTimeout(timer);
    timer = setTimeout(function(){
      // Do stuff here
    }, 2000);
  });
});
like image 142
Svante Svenson Avatar answered Dec 09 '22 18:12

Svante Svenson


$(document).ready(function() {

    var ajaxQueue;

    $('#domain').change(function() {

        if(!ajaxQueue) {
           ajaxQueue = setTimeout(function() { 
              /* your stuff */
              ajaxQueue = null;
          }, 2000);
        }

    });

});
like image 25
David Hedlund Avatar answered Dec 09 '22 17:12

David Hedlund