繁体   English   中英

如何停止 setInterval

[英]How can I stop setInterval

我正在通过 for 循环创建 canvas。 每 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>

您需要使用 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM