Question

I have an input field where the user types info, something like the following:

$('input').on("keyup", function(){
    // make an ajax call
});

I want the call made less frequently. How should I do it? I tried setTimeout and delay(). Couldn't achieve what I want. Can someone help?

Was it helpful?

Solution

You can use this code :

$('input').keyup(function(e){
    var timer = $(this).data('__timer');
    clearTimeout(timer);
    $(this).data('__timer', setTimeout(function(e){
        //Your ajax here.
        console.log(e)
    }.bind(this, e), 500));
})

OTHER TIPS

You can use a timer to delay the AJAX call until a certain amount of time has passes since the last keyup:

  $('input').keyup(function() {
      // delay the search unless 0.5 seconds have passed since last keyup
      clearTimeout($.data(this, 'timer'));
      $(this).data('timer', setTimeout(<AJAX function call>, 500));
  });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top