The basic question is in the title. I use a function to define a p5.js instance with a particular set of parameters. The sketch itself runs an in-browser video game. When any one out of a set of events occurs in the game, the sketch is removed, ending the game. Given an array of parameter values for the sketch, I use a for-loop to construct a sketch defined using each element of the array. I expected that in a single iteration of the for-loop, the defined sketch would complete (i.e. run until removal) before the for-loop progresses and the next sketch is defined and run. However, what actually happens is that as soon as a sketch is defined, the loop progresses and defines the next sketch. This results in all sketches running in the browser simultaneously.
How do I ensure that each sketch finishes before the next one runs? My guess is that I probably need to pass some variables to each sketch that call noLoop() and Loop() appropriately, but Iām not sure. Below is a minimal working example in the form of an HTML file:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/p5@1.2.0/lib/p5.js"></script>
</head>
<body></body>
<script>
/* Function to define sketch with parameter 'a' */
function defineSketch(a) {
let sketch = function(p) {
let x = 100;
let y = 100;
p.setup = function() {
p.createCanvas(700, 410);
};
p.draw = function() {
p.background(0);
p.fill(255);
p.rect(x, y, a*50, a*50);
};
/* Remove sketch on mouse press */
p.mousePressed = function() {
p.remove();
};
};
}
/* Initialize sketch variable */
let trialSketch;
/* Array of parameters */
let param_seq = [0, 1, 2];
/* For loop to sequentially run sketches with different parameters */
for(let i = 0; i < param_seq.length; i++ ) {
trialSketch = defineSketch(param_seq[i]);
new p5(trialSketch);
}
</script>
</html>