JS SetInterval加快

Rob*_*bin 3 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);
Run Code Online (Sandbox Code Playgroud)

};

小智 5

您使用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
};
Run Code Online (Sandbox Code Playgroud)

timerRef可能是undefinednull对于clearInterval()