我怎样才能停止 setInterval

How can I stop setInterval

我正在通过 for 循环创建 canvas。 每秒显示每 20 个不同大小的圆圈。 当圈子总数变为 100 时,我需要 stop/escape 循环。

我试过像下面这样停止间隔。但是,它继续在控制台中循环,即使圆形停止显示。

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>

您需要使用setIntervalreturn来清除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>