Search code examples
javascriptscopesettimeoutdelay

Javascript:Push items in a list and print them with delay


I want to push items in a list using a for loop and print every step with a delay. Instead I get in every iteration the complete list.I guess this is a scope problem but I cant figure a solution.

Here is my code:

function printNumber(num,i){

    setTimeout(()=>console.log(num),500*i);
}


let numbers = [50];

for(let i=1; i<=10; i++){

    printNumber(numbers,i);
    numbers.push(i);
}



Solution

  • That's because Javascript passes arrays by reference*, which means that the callback, which runs long after the loop is concluded, will all point to the same, updated, value of the array.

    You need to copy the array every time to use the intermediate state. You can call printNumber this way:

    printNumber([...numbers], i);
    

    So that it will make a new copy of the array and iterations won't mess with each other.

    * see Brian Thompson's comment for further clarification