Search code examples
javascriptasynchronousecmascript-6settimeout

Why is my setTimeout function not waiting for the time specified?


I have a for loop and I want to print its i'th value after a delay but with setTimeout() function, it waits for specified time but then every value of i prints without any delay. Is this because setTimeout() is an Async function and by the time it completes its first countdown, the time for all other values is also over.

for(let i=0;i<10;i++){
   setTimeout(()=>{
     console.log(i);
   },10);
}

OUTPUT: (10ms Gap) 1-2-3-4-5

OUTPUT REQUIRED: 1 - 10ms Gap - 2 -10ms Gap--... So on. Kindly provide the reason for solution.


Solution

  • You are correct that the setTimeout is asynchronous, therefore every console.log(i) is set to run at basically the same time. I find it easier to use setInterval in your scenario:

    let i = 0;
    let myInterval = setInterval(() => {
        console.log(i);
        i++;
    
        if (i === 10) {
            clearInterval(myInterval);
        }
    }, 10);