Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to call the same function sequentially with different arguments while using setTimeout()

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The expected output would be:

1
2
3
4
5
6

>Solution :

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);
})();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading