I am attempting to use setTimeout in a recursive function call where the main function is called recursively and subfunctions are also called recursively. Below is the code I am working on:
this.myArray = Array(2).fill(undefined);
StartFunction(len: number) {
console.info('in StartFunction ', len);
this.SubFunction_1(len);
this.SubFunction_2(len);
if (len > 0) {
this.myArray.pop();
this.StartFunction(this.myArray.length);
}
}
SubFunction_1(input: number) {
console.warn('in SubFunction_1 ', input);
}
async SubFunction_2(input: number) {
console.error('in SubFunction_2 ', input);
if (input > 0) {
input--;
// const promise = new Promise((resolve, reject) => {
setTimeout(() => {
this.SubFunction_2(input);
// resolve('getData completed ' + input);
}, 1000);
// // const data = await promise;
// // console.log(data);
}
}
My goal is to execute the functions in order and wait for SubFunction_2 to complete before moving forward. I have also created a stackblitz for reference:
https://stackblitz.com/edit/angular-v7ycuk?file=src%2Fapp%2Fapp.component.ts
I have tried a few things (commented out) but have not been able to achieve the desired outcome. Any suggestions?