Reputation: 26708
I would like to call the function example
multiple times with different arguments, while using setTimeout
inside logic
. I want this to be sequential (after the first call is made and finished, the second call can begin, and so on). In the following code snippet, example
seems to be going through both arrays element-wise:
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
function logic(i, arr) {
setTimeout(() => {
console.log(arr[i]);
}, (i + 1) * 300);
}
function example(arr) {
for (var i = 0; i < arr.length; i++) {
logic(i, arr);
}
}
setTimeout(() => {
example(arr1)
}, 3000);
setTimeout(() => {
example(arr2)
}, 3000);
1
4
2
5
3
6
I am aware that I could just set the timer of the second call to 6 seconds for example, and it will work, but I wonder:
Is there is another way to find out that the call to example
is done and then trigger the next one? Without statically defining some delays and maybe even without setTimeout
?
The expected output would be:
1
2
3
4
5
6
Upvotes: 0
Views: 129
Reputation: 24362
logic
needs to let the caller know when it's done, then example needs to let the caller know when it's done. Promises will help you here.
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
function logic(i, arr) {
return new Promise(resolve => {
setTimeout(() => {
console.log(arr[i]);
resolve();
}, (i + 1) * 300);
});
}
async function example(arr) {
for (var i = 0; i < arr.length; i++) {
await logic(i, arr);
}
}
(async function() {
await example(arr1);
await example(arr2);
})();
Upvotes: 2