Created
May 5, 2018 21:19
-
-
Save afaur/ff126a0c2d016e3b7fa66f679012c599 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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')); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
> 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