Legit, it takes some serious getting used to if you haven't worked with it before. You could also write it like this, which might help with David's clustering issue: 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 const CreateExplosion = () => {
dX = randomInteger ( 350 )
dY = randomInteger ( 350 )
x = targetToken . get ( "left" ) - 175 + dX ;
y = targetToken . get ( "top" ) - 175 + dY ;
sound = findObjs ({ type : "jukeboxtrack" , title : "Explosion" })[ 0 ];
sound . set ({ playing : true , softstop : false });
spawnFx ( x , y , "explosion-fire" );
};
let numExplosions = 30 ;
const ChainExplosions = () => {
if ( numExplosions -- ){
CreateExplosion ();
setTimeout ( ChainExplosions , 500 );
}
};
ChainExplosions (); Lines 11-20 will probably make your brain hurt, but let me explain the difference. In the original code I posted, the execution of immediately schedules 30 timeouts at 0ms, 500ms, 1000ms, ... 15000ms. setTimeout() sets the minimum amount of time before the function gets called. That means if you specified 500, it will always be at least 500ms before being called (usually ~507ms or so), but it could be much, much longer. The reason is that Javascript is single threaded, and basically uses cooperative multitasking. If something is running and doesn't return control to the virtual machine, then whatever is waiting to run won't get run for a while. If you've seen the "possible infinite loop detected" error when something runs for too long, that's exactly what's happened. There is a watchdog timer inside the sandbox virtual machine that is monitored by another process. If control doesn't return to the virtual machine so it can reset that timer, the external process kills the sandbox. The code here on lines 11-20 is set up to instead have each explosion schedule the next explosion when it happens. That means if he first one doesn't go off until 1673ms, the earliest the next could happen would be 2173ms. Line 11 sets up the number of times to call the explosion Line 13 defines the chain explosions function. Line 14 checks that there are still explosions to schedule and decrements the number of explosions left to do. Line 15 calls the function to create the explosion (it gets targetToken from the outer scope via a Closure) Line 16 schedules the next explosion for 500ms from this one Line 20 starts the first explosion.