Home > Mobile >  How to print values alternating between two arrays with different delay/timeout values
How to print values alternating between two arrays with different delay/timeout values

Time:09-21

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 ?

CodePudding user response:

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

CodePudding user response:

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];

// 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();
        }
    }, 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();
        }
    }, 3000)
};

// start the initial timeout
setATimeout();

Note that this will not work quite right if your arrays are of different length. The question is a little unclear in that regard.

CodePudding user response:

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

  • Related