So as you all may know, there is a limit regarding how for loops work in p5.js.
For example, this code draws many circles on top of each other on the canvas, but the process quickly halts & the canvas vanishes due to the for loop being too large.
function setup() {
createCanvas(400, 400);
background(100);
variable = 0;
for (i = 0; i < 1000000; i++) {
circle(0, 0, 100);
}
}
But when you add //noprotect as a comment anywhere, it will continue & keep going until finished (may cause lag when running on less powerful hardware).
But my questions are: what is the exact limit for for loops? What about while loops that could potentially be infinite? I’ve seen many cases where p5.js fails to protect from infinite while loops.
Is there an explanation to how //noprotect exactly works? Searching in the p5.js reference shows no results found.
While the for / while loops are being executed the sketch is blocked from processing mouse, key, touch and pointer events from your input devices.
So if you have a large for or while loop that requires significant CPU time then the sketch may become inactive and this is detected by the browser which generally halts the script / sketch.
It is the responsibility of the programmer to write safe code rather than p5js / JavaScript to pull your sketch out of the mire.
There is no exact number, it very much depends on the code complexity inside the loop body. The more complex the code the longer it takes to execute therefore the smaller the number if iterations allowed.
Also some browsers allow the user to adjust the time allowed before it stops an unresponsive script.
If you have a code-segment that takes more than a few seconds to execute the solution is to run it in a Web Worker thread but that is more advanced topic.