I'm trying to use kaboom.js for the first time creating some moving rectangles, but after some time the browser will say that javascript is slowing down everything and blocks it. I'm guessing this is because when an object exists the screen it doesn't get deleted, but I don't see that in another kaboom scripts
code
import kaboom from "https://unpkg.com/kaboom@next/dist/kaboom.mjs";
let w, h, direction;
let speed = 20;
let spawnSpeed = 3;
let mode = 'x';
kaboom();
function addRect() {
switch (mode) {
case 'x':
w = 40;
h = rand(15, 25);
mode = 'y';
direction = RIGHT;
break
case 'y':
w = rand(15, 25);
h = 40;
mode = 'x';
direction = DOWN;
break;
}
add([
rect(w, h),
area(),
outline(4),
pos(
rand(0, width()-width()/2),
rand(0, height()-height()/2)
),
origin("botleft"),
color(rand(0,255), rand(0,255), rand(0,255)),
move(direction, speed),
]);
wait(spawnSpeed, addRect);
speed += 10;
if (spawnSpeed >= 1) {
spawnSpeed -= 0.3;
};
speed += 0.3;
}
addRect();
When you see that the whole system slows down it means that surely there is a memory leak or a recursive function calling itself (at least in javascript). The time it takes before everything freezes depends on the amount of RAM you have available.
As you can see from the screenshot kaboom has come to consume 6GB of ram (which causes the slowdown of the entire system) this is because you never remove the rectangles you add and, from what you have written in the code (spawnSpeed) you also do it faster and faster.
Also refer to the documentation and avoid copying and pasting other scripts: https://kaboomjs.com/doc#destroy