How can i print number in regular interval through setTimeout function?

前端 未结 4 928
梦毁少年i
梦毁少年i 2021-01-29 12:26
var i=0;
function counter(){
    for( i;i<100;i++){
        setTimeout(()=>{
            console.log(i);
        },2000)
    }
}

counter();

i wa

相关标签:
4条回答
  • 2021-01-29 12:30

    Use setInterval(), like this:

    var i=0;
    var intervalID;
        
    function printAndIncrement()
    {
        // Stop interval procedure when "var i" reach to 100.
    
        if (i > 100)
        {
            clearInterval(intervalID);
            return;
        }
    
        console.log(i);
        i++;
     }
        
     intervalID = setInterval(printAndIncrement, 1000);

    0 讨论(0)
  • 2021-01-29 12:32

    How can i print in interval of 2 second?

    'Drift' due to CPU time is a consideration.

    If your use case is running code spaced 2 seconds apart minimum, use setTimeout():

    let ctr = 1
    
    const fn = () => {
      console.log(ctr++)
      setTimeout(fn, 2000) // set the next run
      }
    
    setTimeout(fn, 2000) // set 1st run

    If your use case is running code spaced 2 seconds apart maximum, use setInterval():

    let ctr = 1
    
    const fn = () => console.log(ctr++)
    
    setInterval(fn, 2000)

    More on JS CPU Timer drift here: https://johnresig.com/blog/how-javascript-timers-work/

    Cheers,

    0 讨论(0)
  • 2021-01-29 12:45
    function counter(){
    for( let i=0;i<100;i++){
        setTimeout(()=>{
            console.log(i);
        },2000)
    }
    }counter();
    

    Just change var to let

    0 讨论(0)
  • 2021-01-29 12:53

    const printNumbersForEvery2Sec = (n) => {
      for (let i = 1; i <= n; i++) {
        setTimeout(() => {
          console.log(i)
        }, i * 2000)
      }
    }
    printNumbersForEvery2Sec(10);

    Taken from here

    0 讨论(0)
提交回复
热议问题