JavaScript – How to Use SetInterval Multiple forEach()

javascript

Hello everybody hope all are good today ?

This is my code :

const A = [
{value:'A0'},
{value:'A1'}];

const B = [
{value:'B0'},
{value:'B1'}];

const C = [
{value:'C0'},
{value:'C1'}];

let ResultFinal = async () => {

    A.forEach(async (A) => {     
    B.forEach(async (B) => {
    C.forEach(async (C) => { 
    
    setInterval(function() {  TableResult(A,B,C) }, 2000); 
                        

    })})})      
            } 

let TableResult = async (A,B,C)  => {
        
const Result = 
    [{ 
        A : A.value,
        B : B.value,
        C : C.value,
    }];

console.table(Result);

}

Ok so the problem is when i run my script i get all result (21 results) in one time. But i want 1 result every X seconds

I mean i want the scrypt execute only " the 1st route and wait X second > execute the 2nd route and wait X second > execute the route number 3 and wait X etc …

Best Answer

The issue with your current code is that you're using setInterval() inside the nested loops, which means that all of the calls to TableResult() are being scheduled at the same time, resulting in all the results being printed at once after the specified interval.

To print the results one at a time with a delay between them, you can use the setTimeout() function instead of setInterval(). Here's an updated version of your code that should achieve the desired behavior:

javascript Copy code

const A = [
  {value:'A0'},
  {value:'A1'}
];

const B = [
  {value:'B0'},
  {value:'B1'}
];

const C = [
  {value:'C0'},
  {value:'C1'}
];

let delay = 2000; // Set the delay between results in 
milliseconds

let ResultFinal = async () => {
  for (let a of A) {
    for (let b of B) {
      for (let c of C) {
        await new Promise(resolve => setTimeout(resolve, 
delay)); // Wait for the specified delay
        await TableResult(a, b, c);
      }
    }
  }
}

let TableResult = async (a, b, c) => {
  const Result = [{ 
    A : a.value,
    B : b.value,
    C : c.value,
  }];

  console.table(Result);
}

ResultFinal();

In this updated version, we're using a for loop instead of forEach() to iterate over the arrays. Inside the loop, we're using await setTimeout() to wait for the specified delay before calling TableResult() with the current values of a, b, and c. This should result in each result being printed separately with a delay between them.

Related Topic