I have a simple setTimeout function in Javascript that just allows me to specify the amount of time to delay whatever action by and then just a callback to use for chaining
function delay(item, callback) {
return new Promise(function(response, reject) {
setTimeout(function() {
console.log(item.message);
response(callback());
}, item.time);
});
}
I'm able to use it fine with nesting callbacks but it starts to become very tedious and ugly to use for longer chains
function delayChain() {
const items = [
{message:"Waited 01 sec", time:1000},
{message:"Waited 02 sec", time:2000},
{message:"Waited 04 sec", time:4000},
{message:"Waited 03 sec", time:3000}
];
delay(items[0], function() {
delay(items[1], function() {
delay(items[2], function() {
delay(items[3], function() {
console.log("Done Waiting");
});
});
});
});
}
I was wondering if it is possible to do something similar but in a recursive way
UPDATE
It seems that something similar can be done without the need of callbacks by using async/await like this
async function delayChainAsync() {
const items = [
{message:"Waited 01 sec", time:1000},
{message:"Waited 02 sec", time:2000},
{message:"Waited 04 sec", time:4000},
{message:"Waited 03 sec", time:3000}
];
for(let item of items) {
await delay(item, function() {});
}
console.log("Done Waiting");
}
But I'm hoping to still make use of the callback chaining like in the original delay function