Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
Correctly delaying setTimeout

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!