最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JS SetInterval Speeds Up - Stack Overflow

programmeradmin3浏览0评论

Could someone explain why the following code behaves correctly for the first few repeats and then speeds up to manic pace? I searched and found that I should clearInterval before setInterval, but it made no difference.

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

Could someone explain why the following code behaves correctly for the first few repeats and then speeds up to manic pace? I searched and found that I should clearInterval before setInterval, but it made no difference.

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);
};
Share Improve this question edited Oct 22, 2020 at 10:25 Mosh Feu 29.4k18 gold badges93 silver badges141 bronze badges asked May 17, 2015 at 11:38 Robin AndrewsRobin Andrews 3,80412 gold badges55 silver badges128 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

You're using setInterval()/clearInterval() wrong. setInterval() returns a timer-reference, this is the one you need to clear:

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 may be undefined, null for clearInterval()

发布评论

评论列表(0)

  1. 暂无评论