javascript - 如何停止 setInterval
问题描述
我正在通过 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>
解决方案
您需要使用 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>
推荐阅读
- laravel - RuntimeException:The "-r" option does not exist
- javascript - javascript选择特定元素
- html - Overlay of div over button with background colour
- python - My python code is not running. It gives me an error below
- elasticsearch - Calculate custom score based on function_score with ElasticSearch
- python - Continuous input
- swift - 在 Swift 中测试 write(to: url)
- django - Django causing noReverseMatch even with correct namespacing
- ios - x 和 y 位置因不同的设备而异
- c# - 无法加载文件或程序集'Remotion.Linq,版本 = 2.1.0.0