-2

Please help me with this problem. After each loop occurance, I wanted to log data with an increase in seconds.

my result (logs data just after 1 second)

for(let i=1;i<=3;i++){
  setTimeout(() => {
    console.log(i) // this logs after each second
  },i*1000)
}

expected result :

  1. after 1 second - print - console.log(1)
  2. after 2 second - print - console.log(2)
  3. after 3 second - print - console.log(3)
user9151444
  • 31
  • 1
  • 9

1 Answers1

1

If you mean to increase the delay between each log, you can compute the sum of arithmetic sequence.

for(let i=1;i<=3;i++){
  setTimeout(() => {
    console.log(i)
  },( i * (1+i) / 2) * 1000)
}

Or use an extra variable to accumulate the sum

let acc = 0
for(let i=1;i<=3;i++){
  setTimeout(() => {
    console.log(i)
  },(acc += i) * 1000)
}

Or even play with async await

function delay(ms){
  return new Promise((resolve)=>{
    setTimeout(resolve,ms);
  });
}

(async ()=>{
  for(let i=1;i<=3;i++){
    await delay(i * 1000);
    console.log(i)
  }
})();
Ricky Mo
  • 6,285
  • 1
  • 14
  • 30