1

Here is the sample after pass to some process which consume time , the values of array return empty

function myFunction() {
  let myArray = [];
  let pastArray = [1, 2, 6, 7, 8, 1, 9, 6, 0]
 pastArray.forEach(item =>{

setTimeout(function(){ myArray.push(item) }, 10000);
 })
  return myArray;
} 

here is the code for print the output of the function...help needed

console.log(myFunction())  

Danford Kija
  • 574
  • 6
  • 15
  • It is not clear what you are trying to achieve. Please elaborate more – Abhishek Sharma May 01 '21 at 15:26
  • What do you expect? You are initializing `myArray` to be an empty array `[]` and push your values asynchronously. Thus, when you call `return` your `push` is still not executed for another 10 seconds. Read about execution stack and eventqueue – derpirscher May 01 '21 at 15:27
  • @AbhishekSharma I want to display array values (array myArray) after call my function on console. – Danford Kija May 01 '21 at 15:27
  • @derpirscher sure ,what I want now is when I call my function to have values ,even though their is delay of 10 seconds – Danford Kija May 01 '21 at 15:29
  • The only way to do this is either using async/await or with a callback. – derpirscher May 01 '21 at 16:59

1 Answers1

0

let myArray = []; // empty array

function myFunction() {
    let pastArray = [1, 2, 6, 7, 8, 1, 9, 6, 0]; // default array values
    let timeoutVal = 10000; // default starting time
    let addTime = 10000; // time to add timeout in loop

    pastArray.forEach(item => {
        setTimeout(function () {
            addMyArray(item); // call the array push function after the calculated timeout
        }, timeoutVal);

        timeoutVal = timeoutVal + addTime; // add time to next item.
    });
}

function addMyArray(item) {
    myArray.push(item);
    console.log(myArray);
}

myFunction(); // call first function that is start to read pastArray and set timeout.
  • 1
    What difference does it make if you increase the timeout with every iteration? `myArray` will still be an empty array after `myFunction` returns. Furthermore, instead of just posting a random bunch of code, it's expected to explain, why an answer would solve the original problem – derpirscher May 01 '21 at 17:01