javascript - JS SetInterval 提速

标签 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);
};

最佳答案

您使用的 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 for clearInterval()

关于javascript - JS SetInterval 提速,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30286530/

相关文章:

node.js - 使用 puppeteer 进行负载测试

javascript - 动态创建的表格单元格在 Firefox 32.0 中不显示

javascript - 在 JavaScript 俄罗斯方 block 中绘制新的俄罗斯方 block

javascript - 如何在 Canvas 中绘制从页面加载的图像

javascript - GitHub 使用哪个库来美化 JavaScript 代码?

javascript - React 何时以及以什么顺序更新 DOM?

regex - Javascript regex.match 有缺陷?

javascript - 如何将动态文本框值分配给相应的模型

javascript - 我正在尝试将上一个和下一个箭头添加到此内容 slider

javascript - 如何通过 KineticJS 基于混合 JavaScript Canvas 代码绘制新线?