How to rewrite to debounce instead of setTimeout?

You probably need debounce to return a promise.

https://lodash.com/docs/4.17.10#debounce

The behavior should be similar to this https://codesandbox.io/s/wy7z7q5zx5 with an interval of 300 mc

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); const asyncValidation = memoize( async value => { await sleep(500); try { ….. } catch (err) { ….. } }); 
  • 2
    it's worth adding what debounce is and what should generally happen in code - Grundy
  • debounce from the lodash library for example lodash.com/docs/4.17.10#debounce - werty
  • 2
    Add a description to the question itself, plus a description of what should generally happen in the code - Grundy
  • 2
    try to make the description in words, not a link: it is unclear what exactly should demonstrate an example and what should be done to see the expected behavior, and, most importantly, what exactly this expected behavior consists of. - Grundy
  • one
    Add a minimal reproducible example , please. And describe the desired behavior. “I want it here” is not a description. The link is too much code. - vp_arth

1 answer 1

If I understand correctly what debounce is:

 const debounce = (fn, ms) => { let dfn = (...args) => { let rest = +dfn.next - Date.now(); dfn.next = (dfn.next ? dfn.next : Date.now()) + ms; setTimeout(() => fn(...args), rest > 0 ? rest + ms : ms); } return dfn; } let fn = debounce( i => console.log(i, Date.now()), 200 ); for (let i = 1; i <= 30; ++i) { setTimeout(() => fn(i)) } console.log(30, 'calls queued'); 

Then try to guess what you need from sleep:

 const debounce = (fn, ms) => { let dfn = (...args) => { let rest = +dfn.next - Date.now(); dfn.next = (dfn.next ? dfn.next : Date.now()) + ms; return new Promise(ok => setTimeout( () => ok(fn(...args)), rest > 0 ? rest + ms : ms )); } return dfn; } const getSleep = ms => debounce( () => Promise.resolve(), ms ); const sleep = getSleep(200); (async() => { let start = Date.now(); await sleep(); await sleep(); await sleep(); await Promise.all([sleep(), sleep(), sleep()]); console.log(`wake up after ${Date.now() - start}ms`); // 1200ms = 200 * 6 })()