【问题标题】:JS SetInterval Speeds UpJS SetInterval 加速
【发布时间】:2015-05-17 11:38:10
【问题描述】:

有人能解释一下为什么下面的代码在前几次重复中表现正确,然后加速到疯狂的速度吗?搜索了一下,发现应该在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);
};

【问题讨论】:

    标签: javascript google-chrome canvas setinterval


    【解决方案1】:

    你用错了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 可能是undefinednullclearInterval()

    【讨论】:

    • 感谢 K3N。我对几点感到好奇(作为一个新手)——为什么我需要在函数中使用变量 timerRef 之前定义它?为什么通过将 setInterval 分配给变量来调用它?分配给变量时会自动调用函数还是仅调用这个函数? (我的问题可能显示了一些相当基本的概念混淆。)
    • @Robin timerRef 在父作用域中声明为在函数内部可用(即能够引用它)。如果在里面,它将是一个本地变量,并且仅对当前调用有效(即,每次都是一个新值)。我自己很少使用分配给 vars 的函数,但 setInterval 引用的是 var 刚刚指向的函数。裁判。然后由 setInterval 调用。这听起来也令人困惑,但只需尝试这些东西。专注于孤立的案例以了解有关它们的一切(这里:范围、执行上下文、异步)。他们最终都会连接起来。我的 2 美分。
    猜你喜欢
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-15
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多