JS SetInterval 提速

JS SetInterval Speeds Up

有人可以解释为什么以下代码在前几次重复时表现正确,然后加速到疯狂的速度吗?我搜索了一下,发现应该先clearInterval再setInterval,但是没有区别。

var begin = window.onload = function() {
  var canvas = document.getElementById("canvas"),
    context = canvas.getContext("2d"),
    width = canvas.width = 600,
    height = canvas.height = 600;

  var stripWidth = Math.floor(Math.random() * (50 - 5 + 1) + 5);
  for (i = 0; i <= (width / stripWidth); i++) {
    context.strokeRect(stripWidth * i, stripWidth * i, width - (2 * i * stripWidth), width - (2 * i * stripWidth));
  }
  clearInterval(begin);
  setInterval(begin, 1000);
};

您使用的 setInterval()/clearInterval() 有误。 setInterval() returns 一个定时器参考,这是你需要清除的:

var timerRef;    // place in parent or global scope so it's accessible inside the function

var begin = window.onload = function() {
  var canvas = document.getElementById("canvas"),
      context = canvas.getContext("2d"),
      width = canvas.width = 600,
      height = canvas.height = 600;

  var stripWidth = Math.floor(Math.random()*(50-5+1)+5);
  for (i = 0; i<= (width / stripWidth); i++){
      context.strokeRect(stripWidth * i, stripWidth *i, 
                         width - (2 * i *  stripWidth), width - (2 * i * stripWidth));
  }
  clearInterval(timerRef);               // clear timer if any
  timerRef = setInterval(begin, 1000);   // store timerRef
};

timerRef 对于 clearInterval()

可能是 undefinednull