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

Print two array one after another(with interval) in javascript

I have two array :
numbers:[1,2,3,4]
letters: ["a","b","c","d"]

I want to print as the numbers array first with time interval of 3 sec and then print letters array.
output should be: 1(3sec interval) 2(3sec interval) 3(3sec interval) 4(3sec interval) 5(3sec interval) a b c d.

I tried with following code:

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

const result = document.getElementById("frame")
const numbers = [1,2,3,4], letters = ["a","b","c","d"]

const function1 = () =>
  letters.forEach((c, i) => setTimeout(() => console.log(c)));
const function2 = () =>
  numbers.forEach((c, i) => setTimeout(() => console.log(c), i * 3000));

async function main(){
    await function1();
    await function2();
}
main();

>Solution :

You can do this

const numbers = [1,2,3,4], letters = ["a","b","c","d"]

const function1 = () => new Promise((resolve) => {
  letters.forEach((c, i) => setTimeout(() => console.log(c), i * 3000));
  setTimeout(resolve, letters.length * 3000)
})
  
const function2 = () =>
  numbers.forEach((c, i) => setTimeout(() => console.log(c)));

async function main(){
    await function1();
    await function2();
}
main();
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