Search code examples
javascriptlaravelvue.jssearchtypehead

Search typehead trigger time in jquery


Is there any way how to trigger the event in every 3 seconds in laravel vuejs, but I've been using Jquery in my script.The problem is when I search and input any string, since I've been using keyup on input type it will trigger the event every characters I've type. All I want, It will trigger when you stop typing for at least 3 seconds, else if you continued typing it will not trigger the event, is there any way to achieve this? it will very helpful for me.

Currently I've been tried settimeout but every time I've type will get multiple results after setting the time.

<input type="text" class="form-control required-field" name="driver_fullname" placeholder="Enter fullname" v-model="formFields.fullname" v-on:keyup="typehead"/>

script

   typehead(){
        let vm = this;
        let driveInfo = vm.formFields.fullname;

         setTimeout(() => {
            axios.put(BASE_URL + '/transportation/driver/autoComplete/' + driveInfo).then(response => {
            console.log(response.data);
            });
        }, 500);
    },

Solution

  • Sounds like what you really want is to debounce the user input to prevent an API call on every keystroke.

    Check out https://www.npmjs.com/package/debounce

    If you really want to delay by three seconds after the user stops typing, one way would be to use clearTimeout().

    Add typeaheadTimeout: null to your component data.

    Then:

    typehead() {
      let driveInfo = this.formFields.fullname;
    
      if (this.typeaheadTimeout) {
        clearTimeout(this.typeaheadTimeout);
      }
    
      this.typeaheadTimeout = setTimeout(() => {
        axios.put(BASE_URL + '/transportation/driver/autoComplete/' + driveInfo).then(response => {
          console.log(response.data);
        });
      }, 3000);
    },