7

I have an input box. After the user has stopped typing, I want to perform an HTTP request and await the results.

Here's a jsbin

Since network requests aren't allowed on jsbin, I've used setTimeout() instead.

var log = console.log.bind(console)

var delayedResults = new Promise(function(resolve) {
  setTimeout(function(){
    resolve('Wooo I am the result!')
  }, 3000);
});

document.querySelector('input').addEventListener('input', _.debounce(async function(){
  log('Doing search')
  var result = await delayedResults
  log('Result is', result)
}), 500);

However when I type in the box, 'Doing search' appears immediately every character - I want it to only appear after the 500ms has expired.

How can I use debounce and await?

error
  • 694
  • 4
  • 14
mikemaccana
  • 110,530
  • 99
  • 389
  • 494
  • Does this answer your question? [Write async function with Lodash in a Vuejs component](https://stackoverflow.com/questions/50422806/write-async-function-with-lodash-in-a-vuejs-component) – Ben Racicot Mar 07 '22 at 16:58
  • 1
    @BenRacicot that’s a newer question. So that question is a duplicate of this, depending on whether the asker confirms. – mikemaccana Mar 07 '22 at 17:05

1 Answers1

9

The problem was at the last line:

}), 500);

You should close debounce function call after time argument was specified:

}, 500));

var log = console.log.bind(console);

var delayedResults = new Promise(
  function(resolve) {
    setTimeout(function() {
      resolve('Wooo I am the result!');
    }, 3000);
  }
);

document.querySelector('input')
  .addEventListener('keydown', _.debounce(async function() {
    log('Doing search');
    var result = await delayedResults;
    log('Result is', result);
  }, 500));
<script src="https://cdn.jsdelivr.net/lodash/4/lodash.min.js"></script>
<input>
G07cha
  • 4,009
  • 2
  • 22
  • 39