1

I am trying to print elements from two arrays, with each array having different delays of some time.

Like I have two arrays A and B. First element of array A should print, and then after 3000ms first element of array B should print, and then it repeats.

A=[a,b,c,d],
B=[1,2,3,4]

Expected Output

How to achieve this, can someone help me ?

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260

3 Answers3

1

Since you know the two arrays' combined timeout per loop/repeat is 5000ms, and array B begins 3000ms after A, you could simply do something like this:

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

a.forEach((v, i) => setTimeout(() => console.log(v), 5000 * i));
b.forEach((v, i) => setTimeout(() => console.log(v), 5000 * i + 3000));

Otherwise you can implement a promise or async/await version of sleep/wait: What is the JavaScript version of sleep()?

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
0

To do something after a delay, you can use setTimeout/clearTimeout or setInterval/clearInterval.

For example, to do it with timeouts, you could try something like this:

// data
const a = ['a', 'b', 'c', 'd'];
const b = [1, 2, 3, 4, 5, 6];

// array indices that will increment
let indexA = 0;
let indexB = 0;

// this function sets up a timeout to print an item from A after 2 seconds
const setATimeout = () => {
    setTimeout(() => {
        // print the item
        console.log(a[indexA]);
        // increment the index
        indexA += 1;
        // if array B is not done, set up a timeout for array B
        if(indexB < b.length) {
            setBTimeout();
        } else if (indexA < a.length) {
            setATimeout();
        }
    }, 2000);
}

// this function sets up a timeout to print an item from B after 3 seconds
const setBTimeout = () => {
    setTimeout(() => {
        // print the item
        console.log(b[indexB]);
        // increment the index
        indexB += 1;
        // if array A is not done, set up a timeout for array A
        if(indexA < a.length) {
            setATimeout();
        } else if (indexB < b.length) {
            setBTimeout();
        }
    }, 3000)
};

// start the initial timeout
setATimeout();
nullromo
  • 2,165
  • 2
  • 18
  • 39
  • This is not going to alternate between the two arrays though like OP wants to. – Gunnar B. Sep 21 '22 at 07:01
  • Good point. I'll update it. – nullromo Sep 21 '22 at 07:03
  • the snippet which you shared is exactly what i am looking for , as of now i have same length arrays . what will be the fix for two different length arrays ? Thank You for the code snippet it helped me. – stackflow_black Sep 21 '22 at 11:36
  • You just need to add a bit of extra conditional logic. I updated the answer accordingly. – nullromo Sep 21 '22 at 20:44
  • i faced one issue when we run locally its working fine, when we are trying to deploy on server its throwing an error 'setBTimeout' was used before it was defined @typescript-eslint/no-use-before-define – stackflow_black Sep 22 '22 at 14:54
  • Ah yes, you will run into that here. You can either disable the rule for that line (by adding `// eslint-disable-next-line @typescript-eslint/no-use-before-define` on the line before it), disable the rule entirely, or change the `variables` option (documentation: https://eslint.org/docs/latest/rules/no-use-before-define#options, SO reference: https://stackoverflow.com/a/42981319/4476484) if that suits your needs. Unfortunately with this specific code, there's no way to avoid that warning (that I know of). But you know the function is defined. Personally, I would add the ignore comment. – nullromo Sep 22 '22 at 19:22
0

So here you can use setTimeout which is inbuilt in

javascript

window.setTimeout(function(){
// do something

    },delaytime)

nodejs

setTimeout(function(){
// do something
    
        },delaytime)

let array1 = ['a','b','c','d']
let array2 = [1,2,3,4]
var i = 0;

(function loopwithdeley() {
    if (++i < array1.length+1) {
        setTimeout(()=>{
            console.log(array1[i-1])
            setTimeout(()=>{
            console.log(array2[i-1])
            loopwithdeley()
        }, 3000);
        }, 2000);
    }
})();