javascript - Debounce function implemented with promises -
i'm trying implement debounce function works promise in javascript. way, each caller can consume result of "debounced" function using promise. here best have been able come far:
function debounce(inner, ms = 0) { let timer = null; let promise = null; const events = new eventemitter(); // need this? return function (...args) { if (timer == null) { promise = new promise(resolve => { events.once('done', resolve); }); } else { cleartimeout(timer); } timer = settimeout(() => { events.emit('done', inner(...args)); timer = null; }, ms); return promise; }; }
ideally, implement utility function without introducing dependency on eventemitter (or implementing own basic version of eventemitter), can't think of way it. thoughts?
i found better way implement promises:
function debounce(inner, ms = 0) { let timer = null; let resolves = []; return function (...args) { // run function after amount of time cleartimeout(timer); timer = settimeout(() => { // result of inner function, apply resolve function of // each promise has been created since last time inner function run let result = inner(...args); resolves.foreach(r => r(result)); resolves = []; }, ms); return new promise(r => resolves.push(r)); }; }
i still welcome suggestions, new implementation answers original question how implement function without dependency on eventemitter (or it).
Comments
Post a Comment