为什么定时器setTimeout返回第一个值" 2"

时间:2015-11-30 10:10:03

标签: javascript settimeout

代码下方。它应该记下从0到19的控制台号码。实际上它确实如此。但它在控制台中打印的第一个数字是多少?

var i = 0;

var timerId = setInterval(function () {
    console.log(i++);
}, 100);

setTimeout(function() {
    clearTimeout(timerId)
}, 2100);

2 个答案:

答案 0 :(得分:0)

虽然您的代码按预期工作,但在某些情况下您可能无法打印所有数字。检查计数器值然后清除当时的间隔可能会更好(javascript中的时间并不像您希望的那样精确)

你可以尝试这样做,以确保你的间隔只能运行一次,并且你不会超过你的最大值。

function Counter(start, maxValue, ticks) {
  this.value = start || 0;
  this.max = maxValue;
  this.ticks = ticks;
  var interval;
  
  this.stop = function() {
    if (!interval) {
      return;
    }
    clearInterval(interval);
    console.log('stopped counter');
  };
  
  this.increase = function() {
    this.value++;
    console.log(this.value);
    if (this.value >= this.max) {
      this.stop();
    }
  };
  
  this.start = function() {
    if (interval) {
      return;
    }
    console.log('starting counter');
    interval = setInterval(this.increase.bind(this), this.ticks || 0);
  };
}

var counter = new Counter(0, 20, 100);
counter.start();

答案 1 :(得分:-1)

来自setInterval文档

  

重复调用函数或执行代码片段,每次调用该函数之间都有固定的时间延迟。返回intervalID。