Search code examples
javascriptasynchronoussequential

How do I execute a function for every element in an array with a 2 second delay and then repeating


I am trying to write a program with the following steps. Each step involves iterating over an array with delay between each iteration. However, I want the three main steps themselves to not execute until the previous step has finished, meaning that the previous step has iterated over all of its elements.

  1. print out numbers in array //2second pause
  2. remove odd numbers from array //2second pause
  3. print out remaining numbers in array

I want each step to execute after the previous one has finished and 2 a second delay.

I also want each number to print to the console 1 second after the previous number has printed like so

const array = [1,2,3,4,5,6,7,8,9,10];

//expected output

//first process
1
//1 sec delay
2
//1 sec delay
3
//1sec delay
…
10
//1sec delay

//first process ends 2 sec delay

//second process remove odd numbers from array

//second process ends 2 sec delay

//third process print all remaining numbers in array

0
// 1 sec delay
2
// 1 sec delay
4
//1 sec delay
…
10
//1 sec delay



Solution

  • function delay(t) {
      return new Promise(function(resolve) {
        setTimeout(resolve, t);
      });
    }
    let item = [1, 2, 3];
    
    
    function executeWithDelay(f) {
      return Promise.all([f(item), delay(2000)])
    }
    
    executeWithDelay(firstProcess)
      .then(_ => executeWithDelay(secondProcess))
      .then(_ => executeWithDelay(thirdProcess))
    
    function firstProcess(item) {
      console.log('firstProcess')
    }
    
    function secondProcess(item) {
      console.log('secondProcess')
    }
    
    function thirdProcess(item) {
      console.log('thridProcess')
    }

    I don't know if it is what you want but this basically use Promise.all to resolve your function with a minimum delay of 2s everytime. Then it is just a promise chaining. You just have to implement your functions1/2/3 to print the number with a setTimeout (and return the promise !). You should be able to modify what i gave you to make it work for your example ;)