0

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
1

1 Answer 1

2

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);
})();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.