& quot; Alive & quot; js search. How to implement with async js?

  • 0
    Good day, gentlemen.
    There is such a problem. It is necessary to implement "live" search in js. Yes, I know a lot of options for its implementation on the Internet, but I need a specific version of it.
    The essence of the task is this: when the oninput event is triggered, a script should be launched that will wait 1.5 seconds for the event to fire again. If the event is triggered, wait another 1.5 seconds, etc. But if the event did not occur, then we receive data from the search bar and send it (exactly how, not the point).
    & lt; input id = "search" & gt; // search string

    let target = document.querySelector('#search');
    target.oninput = function () {
        let val = this.value.trim();
    }

    I came to the conclusion that it might be necessary to implement this using asynchronous js code. But I haven't worked with him yet. I will be glad to advice, help, possible solutions.
    Thanks in advance.
    JavaScript Anonymous, Aug 24, 2020

  • 1 Answers
  • 0
    let target = document.querySelector('#search');
    let timerId = null;

    target.oninput = function () {
    let inputValue = this.value.trim();
    let lastTime = performance.now();

    if (timerId) {
    clearTimeout(timerId);
    }

    timerId = setTimeout(function() {
    if (performance.now() - lastTime > 1500 && inputValue) {
    console.log('Send', inputValue);
    }
    }, 1500);

    }
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!