How to overwrite setTimeout before it reach the time set?

Viewed 7300

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!

6 Answers

I change the timeout but I check with interval

var goal={
    cb: cb
,   timeout: (+new Date())+60000 //one minute from now
,   setInterval(function(){
        if((+new Date())>goal.timeout){cb();}
        })
    };

Now I want to increase, decrease or reset the timeout?

goal.timeout-=1000;
goal.timeout+=1000;
goal.timeout=60000;
Related