如何通过setTimeout函数定期打印数字?

时间:2018-10-09 03:06:27

标签: javascript node.js

var i=0;
function counter(){
    for( i;i<100;i++){
        setTimeout(()=>{
            console.log(i);
        },2000)
    }
}

counter();

我想每隔2秒打印一次i,但它会立即打印

每次打印仅需几微秒。为什么?因为它只调用setTimeout。执行setTimeout仅需几微秒即可完成。电话会议要做的只是安排将来发生的事情。因此,您已在几微秒内安排了10件事,将在未来大约2秒内发生。所有调度大约在同一时间进行。因此,所有控制台日志大约在同一时间发生,即在您计划它们后两秒钟。

  

如何使用for循环在2秒间隔内打印?

1

2

3

4

...在for循环中延迟2秒

4 个答案:

答案 0 :(得分:1)

使用setInterval(),如下所示:

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);

答案 1 :(得分:1)

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

取自Clear cup with a white coffee sleeve, yellow outline around the coffee sleeve and a cutoff view of the picture that should be the pattern

答案 2 :(得分:1)

  

如何在2秒的间隔内打印?

由于CPU时间造成的“漂移”是一个考虑因素。

如果您的用例运行的代码间隔为2秒最小,请使用setTimeout()

let ctr = 1

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

setTimeout(fn, 2000) // set 1st run

如果您的用例正在运行的代码间隔为2秒最大值,请使用setInterval()

let ctr = 1

const fn = () => console.log(ctr++)

setInterval(fn, 2000)

有关JS CPU计时器漂移的更多信息,请点击此处:https://johnresig.com/blog/how-javascript-timers-work/

干杯

答案 3 :(得分:0)

function counter(){
for( let i=0;i<100;i++){
    setTimeout(()=>{
        console.log(i);
    },2000)
}
}counter();

只需将var更改为let