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

前端 未结 4 1094
梦毁少年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: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,

提交回复
热议问题