How can I refuse to use async / wait?

I have an input field. After the user has stopped typing, I want to execute an HTTP request and wait for the results.

Here jsbin

Since network requests are not allowed in jsbin, I used it instead setTimeout().

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 enter in the field “Search Execution”, each character appears at once - I want it to appear only after 500 ms.

How can I use debounce and wait?

+6
source share
1 answer

The problem was in the last line:

}), 500);

You must close the function call debounceafter defining the time argument:

}, 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>
Run codeHide result
+5

All Articles