首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >JS SetInterval加速

JS SetInterval加速
EN

Stack Overflow用户
提问于 2015-05-17 11:38:10
回答 1查看 3.2K关注 0票数 4

有人能解释一下为什么下面的代码在前几次重复时行为正确,然后加速到疯狂的速度吗?我搜索并发现,我应该在clearInterval之前setInterval,但这没有什么区别。

代码语言:javascript
运行
复制
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);
};
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-05-17 11:41:42

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

代码语言:javascript
运行
复制
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可能是undefinednullclearInterval()

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30286530

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档