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

前端 未结 4 930
梦毁少年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);

提交回复
热议问题