I was inspired by @James 's solution, which is partially wrong because the log messages are in the reverse order, but he does not use Promise
s. I still think that @Redu 's solution should be the accepted one (after all if you can use Promise
s, that is perfect), but this one is interesting too in my opinion:
const foo1 = {
incrementalTimeout: 0,
nextActions: [],
log(text) {
const textLog = () => { console.log(text); };
if (this.incrementalTimeout == 0)
textLog();
else
this.nextActions.push(textLog);
return this;
},
wait(time) {
let newObj = {...this, incrementalTimeout: this.incrementalTimeout + time, nextActions: []};
setTimeout(() => { newObj.nextActions.forEach((action) => action()); } , newObj.incrementalTimeout);
return newObj;
}
}
foo1.log('breakfast').wait(1000).log('lunch').wait(3000).log('dinner');
The idea is that I do not immediately log text
but I push
a lambda with the console.log
in an array that is going to be called after the correct timeout expires.
I run all the log
and wait
operations one after the other, but I keep track of the seconds to wait before executing the actions. Every time a new wait
is called, the incrementalTimeout
is increased by time
. To keep the nextActions
belonging to different time frames separated, I return a newObj
every time, more or less like @James does.