JS SetInterval加速

时间:2015-05-17 11:38:10

标签: javascript google-chrome canvas setinterval

有人可以解释为什么以下代码在前几次重复时表现正确,然后加速到狂躁速度?我搜索并发现我应该在setInterval之前使用clearInterval,但它没有任何区别。

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

};

1 个答案:

答案 0 :(得分:4)

您使用的是setInterval() / clearInterval()错误。 setInterval()返回一个计时器引用,这是您需要清除的那个:

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可能是undefinednull可能是clearInterval()

相关问题