Как я могу остановить setInterval - PullRequest
0 голосов
/ 03 мая 2020

Я делаю холст для l oop. Каждые 20 кругов, каждый из которых имеет разный размер, появляются каждую секунду. Мне нужно остановиться / убежать l oop, когда общее количество кругов станет равным 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 Ответ

3 голосов
/ 03 мая 2020

Вам нужно использовать возвращаемое значение setInterval, чтобы очистить идентификатор.

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>
...