简体   繁体   中英

Call search function when user is done Typing

I have the following problem,

I have this piece of code in my Javascript file,

    termChange(evt) {
        this.rows = [];
        this.searchTerm = evt.target.value;
        this.getCases();
    }

This clears out the rows returned after the search takes place, gets the search term through the event taking place and then calls getCases.

This Code block calls another async function, getCases, that gets a response from our server and gets the results back. The html has onChange = {termChange}. However this is where the problem comes in. Every-time you type, it calls it, causing it to fire 8 times while searching. This results in unwanted search results, and duplicates at times. I need to figure out a way to call this event after the user has finished typing. I have tried to setTimeouts, and even use a debounce. However neither I could get to work in order to solve the problem. Any help with this would be huge. Thanks!

It has to automatically search when the user finishes typing without any movements or button presses.

    debounce(func, wait, immediate) {
        var timeout;
        return function executedFunction() {
          var context = this;
          var args = arguments;
          var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
            };
          var callNow = immediate && !timeout;
          clearTimeout(timeout);
          timeout = setTimeout(later, wait);
          if (callNow) func.apply(context, args);
        };
    }

This is the debounce function I wrote. However when I tried to do something along the lines of

    handleTermChange = this.debounce(this.termChange(), 1000, false);

It throws me an error that it can not find target of undefined. So it does not pass the event through and I could not figure out away to do this and make it work, hence my problem with debounce.

Try using on blur event instead of calling event each time the user types.

Debounce is 100% the way to go - it describes exactly what you're trying to do. Maybe you need a longer timer? Or there was something wrong with the debounce function?

I use a 250ms timer on the site I maintain's search box - but if it's a slower API or if it makes major page rewrites, you'd probably want to go larger.

Also check to make sure the input actually changed... eg store the last searched term and abort it in the search function if new input = old input

Use onkeyup event.

HTML:

<input type="text" onkeyup="termChange(event)">

JS:

var timeout = null;
function termChange(evt) {
    clearTimeout(timeout);
    timeout = setTimeout(function () {
          //Your code
    }, 500);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM