P5.js has it's own loop, which calls the draw() function FPS amount times per second. However, there is a function noLoop() which can be placed in the setup()function, which disables P5.js own loop.
So I made my own loop (this is necessary for my project), which looks like follows:
customLoop = function(){
while(somethingIsTrue){
//custom code here
draw();
}
}
So I expect to see the canvas updated quite fast as there is no FPS set. However, the canvas is only redrawn again AFTER the customLoop is done.
Short in short: the canvas doesn't update while the custom loop is still running, it will only show the updates after the custom loop is done.
How can I update the canvas in my own loop continiously?
People have asked for more context, so i'll try my best to explain. I have made my own JS library that makes it easy to create genetic algorithms for neural networks.
The genetical algorithm in my library is set up as follows:
var evol = new Evolution({
size: 50,
mutationRate: 0.05,
networkSize: [4,10,1],
mutationMethod: [Mutate.MODIFY_RANDOM_BIAS, Mutate.MODIFY_RANDOM_WEIGHT],
crossOverMethod: [Crossover.UNIFORM, Crossover.AVERAGE],
selectionMethod: [Selection.FITNESS_PROPORTIONATE],
elitism: 5,
fitnessFunction: function(network){
//something here that computes for every network, AT THE SAME TIME showing it LIVE for the user to watch
}
});
Pay attention to the comment in the fitnessFunction. Then I run a genetic algorithm loop as follows:
var notFinished = true;
while(notFinished){
evol.evaluate();
if(evol.getAverage() > 2000){
notFinished = false;
console.log('done');
}
evol.select();
evol.crossOver();
evol.mutate();
evol.replace();
};
So as you see, my code continously runs the genetical algorithm. But the whole problem lies in the fitness function. This specific genetical algorithm is made to train neural networks how to play snake. So in the fitness function, i'm actually running the neural network until the snake dies. However, for every snake that is tested, I want the user to see how the neural networks are doing. So my fitness function looks something as follows:
fitnessFunction = function(network){
while(snakeIsNotDead){
computeNeuralNetworkOutput();
giveSnakeNewMovementDirectionBasedOnOutput();
// most importantly
redrawTheSnakeWithNewPosition(); // which is redraw() with P5.js
}
So for every generation that is tested, I want to see all the 50 snakes performing. However, all I see after the network is done is the last position the snake had in the last snake evaluation.
drawand draw snakes at those positions.