Skip to content

Instantly share code, notes, and snippets.

@afaur
Created May 5, 2018 21:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afaur/ff126a0c2d016e3b7fa66f679012c599 to your computer and use it in GitHub Desktop.
Save afaur/ff126a0c2d016e3b7fa66f679012c599 to your computer and use it in GitHub Desktop.
// Console.log alias
const l = (...args) => console.log(...args)
// Reject promise with custom error alias
const err = (rej, type) => rej(new Error(type))
// SetTimeout alias
const STO = (fn, ms) => setTimeout(fn, ms)
// new Promise alias
const mkProm = function(func, ...args) { return new Promise(func.bind(this, ...args)) }
class Test {
// timeout ref and amount of time to deflect calls in ms
constructor () { Object.assign(this, {}, { to: null, dt: 1000 }) }
run (query, env={}) {
// Create a promise
return mkProm((res, rej) => {
// Track local ref for timeout
const to = this.to = STO(
// Compare local ref
_ => to === this.to
// If ref is same as what we originally stored then resolve
? res([query])
// If ref is not the same then reject the call
: err(rej, 'Debounced')
, this.dt
)
})
.then(results => l(results) )
.catch(error => l('Script failed'))
}
}
// Try to call the run fn multiple times in succession
const tester = new Test()
l(tester.run('a'));
l(tester.run('a'));
l(tester.run('b'));
> node microtask-debounce.js
Promise { <pending> }
Promise { <pending> }
Promise { <pending> }
[ 'b' ]
Script failed
Script failed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment