Let\'s say I am using the following code to run a couple of promises in series:
let paramerterArr = [\'a\',\'b\',\'c\',\'d\',\'e\',\'f\']
parameterArr.reduce
since this seems to be a requirement of mySpecialFunction I'd implement it there. So that the function delays itself if it is called less than 50ms after the last call
const delayBetweenCalls = (delay, fn) => {
let lastCall = NaN;
return function(/*...arguments*/){
//this and arguments are both forwarded to fn
return new Promise(resolve => {
let poll = () => {
let delta = Date.now() - lastCall;
if(delta < delay){
setTimeout(poll, delta - delay);
}else{
lastCall = Date.now();
resolve( fn.apply(this, arguments) );
}
}
poll();
})
}
}
then:
const mySpecialFunction = delayBetweenCalls(50, function(some, ...args){
return someValueOrPromise;
});
//and your loop stays the same:
parameterArr.reduce(function(promise, item) {
return promise.then(function(result) {
return mySpecialFunction(item);
})
}, Promise.resolve())
so it doesn't matter where/how mySpecialFunction is called, there will always be a delay of at least 50ms before it runs the code inside the passed callback.