Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delay @keyup handler in Vue.js

my view:

ns-input#filterName(type="text", v-model="filterName", @keyup="searchTimeOut()")

in my vue code:

getUsers() {
   .
   .
   .
   API.users.index(params).then(blabla);
   .
   .
   .
},

searchTimeOut() {
  let timeout = null;
  clearTimeout(timeout);
  // Make a new timeout set to go off in 800ms
  timeout = setTimeout(() => {
    this.getUsers();
    console.log("hi")
  }, 800);
},

I want call getUsers() only once after i stop typing and 800 ms. Right now, i'm calling getUsers() every time i write a letter.

like image 903
tomatito Avatar asked Apr 07 '18 19:04

tomatito


Video Answer


1 Answers

You drop this.timer value before clearing the interval. Do this instead:

searchTimeOut() {  
    if (this.timer) {
        clearTimeout(this.timer);
        this.timer = null;
    }
    this.timer = setTimeout(() => {
        // your code
    }, 800);
}
like image 99
oniondomes Avatar answered Oct 11 '22 20:10

oniondomes