Search code examples
javascriptwait

How to Change Interval Time Dynamically in For Loop According to Index/iteration Number?


Since I could not comment, I am forced to write this post. I got the below code which delays/waits exactly 1 seconds or 1000 milliseconds -

let n = 5;
for (let i=1; i<n; i++)
{
  setTimeout( function timer()
  {
      console.log("hello world");
  }, i*1000 );
}

But how can I delay it i*1000 seconds instead of fixed 1000 milliseconds so the waiting depends on iteration number ?

For example, if n= 5 , then I want the loop delay 1 second in 1st iteration. 2 seconds in second iteration, and so on.. the final delay will 5 seconds.


Solution

  • Here is a function that will show immediately, then 1 second later, 2 seconds after than, 3 seconds after that etc. No special math, no promises needed

    const n = 5;
    let cnt=0;
    
    function show() {
      console.log("call "+cnt,"delay: ",cnt,"sec");
      cnt++;
      if (cnt > n) return; // we are done
      setTimeout(show, cnt*1000 ); // cnt seconds later
    }
    show()