0

In the following function

function test1(n, delay) {
  for (let i = 0; i < n; i++) {
    setTimeout(() => {
      console.log(i)      
    }, delay)    
  }  
}

test1(3, 1000)

After 1 second, I immediately console.log 1, 2, and 3 simultaneously.

If I multiply delay by i,

function test1(n, delay) {
  for (let i = 0; i < n; i++) {
    setTimeout(() => {
      console.log(i)      
    }, i * delay)    
  }  
}

test1(3, 1000)

I console.log every i in my loop after 1 second. Why does this work?

Also, why does the code below

function test2(n, delay) {
  let promise = new Promise(resolve => setTimeout(() => {
    resolve()    
  }, delay))
  for (let i = 0; i < n; i++) {
    promise.then(console.log(i))  
  }  
}

test2(3, 1000)

immediately console.log 1, 2, and 3 simultaneously instead of waiting every second to console.log the next i value? Is there a way to console.log the next i value using promise chaining after waiting every second without using async and await?

dev_el
  • 2,357
  • 5
  • 24
  • 55
  • 2
    There are multiple questions and all of them are duplicates. _"Is there a way to console.log the next i value after waiting every second without using async and await?"_: https://stackoverflow.com/a/70213768/16540390 – jabaa Jan 08 '22 at 01:53

1 Answers1

1

The reason why we need to multiply i with delay is by doing that you set a timeout with timeout 1s/2s/3s. In the example, you make the console.log() execute it after 1 seconds, 2 seconds and 3 seconds.....

If you doesn't multiply the i with delay, then all timeout you assign using for loop will executed after 1 (delay) second at the same time (you could almost ignore the execution time of for loop.

Another solution to loop every second is to use setInterval:

let i = 0;
let interval;
function test2(n,delay){
 //Change millisecond to second
   delay*=1000
   interval = setInterval(function(){
       console.log(i);
       i++;
       if(i>n)
       window.clearInterval(interval)
    },delay)
   }
test2(10,1)
James
  • 2,732
  • 2
  • 5
  • 28