如何停止setInterval

时间:2020-05-03 04:51:43

标签: javascript canvas html5-canvas setinterval clearinterval

我正在通过for循环创建画布。 每隔20圈,每秒钟就会显示出不同的大小。 当圆的总数变为100时,我需要停止/退出循环。

我试图像下面那样停止间隔。但是,即使圆形形状不再显示,它也会继续在控制台中循环播放。

if (circles.length > 100) {
  console.log('STOP');
  return;
}

有什么办法吗?

谢谢。

class circle {
  constructor() {
    this.x = 0;
    this.y = 0;
    this.r = 0;
  }
}

const canvas = document.getElementById('canvas');
const context = canvas.getContext("2d");
let colors = ["#96ceb4","#ffeead","#ff6f69","#ffcc5c","#88d8b0"];
let circles = new Array();

window.addEventListener('load', function(){
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;

  context.clearRect( 0, 0, canvas.width, canvas.height );

  function draw() {
    for (let i=0; i < 20; i++) { //20 blocks at a time
      const  item = new circle();

      item.x = Math.floor(Math.random()*canvas.width);
      item.y = Math.floor(Math.random()*canvas.height);
      item.r = Math.floor(Math.random()*50);

      circles.push(item);
      console.log(circles.length);
      if (circles.length > 100) {
        console.log('STOP');
        return;
      }

      context.beginPath();
      context.fillStyle=colors[Math.floor(Math.random()*colors.length)];
      context.globalAlpha=0.5;
      context.arc(item.x, item.y, item.r, 0, Math.PI*2, true);
      context.fill();

    };
  };
  setInterval(draw, 1000);

});
body {overflow: hidden;}
<canvas id="canvas"></canvas>

1 个答案:

答案 0 :(得分:3)

您需要使用setInterval返回值来清除ID。

class circle {
  constructor() {
    this.x = 0;
    this.y = 0;
    this.r = 0;
  }
}

var timer;

function stopTimer(){
clearInterval(timer);
}

const canvas = document.getElementById('canvas');
const context = canvas.getContext("2d");
let colors = ["#96ceb4","#ffeead","#ff6f69","#ffcc5c","#88d8b0"];
let circles = new Array();

window.addEventListener('load', function(){
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;

  context.clearRect( 0, 0, canvas.width, canvas.height );

  function draw() {
    for (let i=0; i < 20; i++) { //20 blocks at a time
      const  item = new circle();

      item.x = Math.floor(Math.random()*canvas.width);
      item.y = Math.floor(Math.random()*canvas.height);
      item.r = Math.floor(Math.random()*50);

      circles.push(item);
      console.log(circles.length);
      if (circles.length > 100) {
        console.log('STOP');
        stopTimer();
        return;
      }

      context.beginPath();
      context.fillStyle=colors[Math.floor(Math.random()*colors.length)];
      context.globalAlpha=0.5;
      context.arc(item.x, item.y, item.r, 0, Math.PI*2, true);
      context.fill();

    };
  };
  timer = setInterval(draw, 1000);

});
body {overflow: hidden;}
<canvas id="canvas"></canvas>