Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overwrite setTimeout before it reach the time set?

So I'm doing an autocomplete search using jquery. I have to set a delay before executing the ajax function because I don't want to hammer my server with calls every time I type on a textbox. Here is my code:

function searchVendor() {
  setTimeout(searchVendor2, 5000);
}

function searchVendor2() {
  var search = $('#inputVendor').val();
  $.ajax({
    type: 'POST',
    url: '/getVendors',
    data: {search: search},
    dataType: 'json',
    success: function(s) {
      $('#inputVendor').autocomplete({source: s});
    }
  });
}

so the function searchVendor is executed onkeyup

<input type="text" class="form-control input-sm" id="inputVendor" onkeyup="searchVendor()">

If I type 3 characters (ex. sas) then the function searchVendor2 is executed 3 times. The 5 seconds delay works but it didn't stop and overwrite the previous setTimeout.

What I want to happen is, if I type a character on the textbox it will be executed after 5 seconds, BUT! if a new character is typed before the 5 seconds, setTimeout is reset again to 5 seconds. As long as the user is typing on the textbox the setTimeout is reset to 5 seconds and it will ONLY be executed if the 5 seconds elapsed without the user typing again.

Thanks to those who can help!

like image 732
Julio de Leon Avatar asked May 25 '17 05:05

Julio de Leon


1 Answers

First, you need to save your timeout id in a global variable, or in a variable that can be accessed later when the function is called again.

Now, whenever your function is called, first you clear that timeout if it exists. Thus you clear any pre-existing timeouts and set a new one every time the function is called.

var myTimeout;

function searchVendor() {
  clearTimeout(myTimeout);
  myTimeout = setTimeout(searchVendor2, 5000);
}

function searchVendor2() {
  var search = $('#inputVendor').val();
  $.ajax({
    type: 'POST',
    url: '/getVendors',
    data: {search: search},
    dataType: 'json',
    success: function(s) {
      $('#inputVendor').autocomplete({source: s});
    }
  });
}
like image 158
Mohit Bhardwaj Avatar answered Sep 29 '22 02:09

Mohit Bhardwaj