From 8eb1e4e7d0243304cce6ff109fd78a32ead7003b Mon Sep 17 00:00:00 2001 From: casperlamboo Date: Wed, 8 Nov 2017 22:11:42 +0100 Subject: [PATCH] add throttle function --- src/utils/async.js | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/src/utils/async.js b/src/utils/async.js index 3375b1f..60e521d 100644 --- a/src/utils/async.js +++ b/src/utils/async.js @@ -42,3 +42,42 @@ export function asyncIterator(array, callback) { // } // return result; // } + +export function createThrottle() { + let next = null; + + return callback => { + const startLoop = next === null; + next = callback; + + if (!startLoop) return; + + return (function loop() { + return next().then(() => { + if (typeof next === 'function') return loop(); + }); + next = true; + })(); + + next = null; + }; +} + +// export function createThrottle() { +// let next = null; +// +// return async callback => { +// const startLoop = next === null; +// next = callback; +// +// if (!startLoop) return; +// +// while (typeof next === 'function') { +// callback = next; +// next = true; +// await callback(); +// } +// +// next = null; +// }; +// }