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

Time:04-08

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:

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();

CodePudding user response:

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

const wait = value => new Promise(resolve => setTimeout(() => resolve(), value))

const function1 = async () => {
    numbers.forEach(async (item, i) => {
        await wait(3000 * i)

        console.log(item)
    })

    await wait(3000 * numbers.length - 1)

    letters.forEach((item) => {
        console.log(item)
    })
}

function1()

CodePudding user response:

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();

CodePudding user response:

  1. If you're just logging all the letters at once the function doesn't need to be async. You can just return the joined array from function2.

  2. function1 does need to be async but that's not what happening in your code. Because setTimeout doesn't behave well inside async functions you need to set up a promise-based delay, and then use that inside the function.

const numbers = [1, 2, 3, 4];
const letters = ['A', 'B', 'C', 'D'];

// Resolve a promise after a given time
function delay(time) {
  return new Promise(res => {
    return setTimeout(() => res(), time);
  });
}

function function1(arr) {

  // Return a promise that is awaited
  return new Promise(res => {

    // Loop over the array
    async function loop(i) {

      // Log the element
      console.log(arr[i]);

      // Call the delay function
      await delay(3000);

      // And then work out if you need
      // to call `loop` again, or resolve the promise
      if (arr.length - 1 === i) {
        res();
      } else {
        loop(  i);
      }

    }

    // Call loop for the first time
    loop(0);

  });

}

function function2(arr) {
  return arr.join(' ');
}

async function main() {
  await function1(numbers);
  console.log(function2(letters));
}

main();

CodePudding user response:

For the record, another simple example where the output is awaited. This assumes your final goal of outputting will be the same for both arrays, just without delays. In case the actual output method is async, you can await that too, but keep a single entry point for both arrays

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

async function output(arr,delayAfterEach){
  for(element of arr){  
     console.log(element);
     if(delayAfterEach)
        await new Promise(r=>setTimeout(r,delayAfterEach));
  }
}

async function main(){
    await output(numbers,3000);
    await output(letters);
}
main();

  • Related