JavaScript is a single-thread language, which means it will only execute one block(function) of code at a given time. JavaScript uses stacks to execute code.
A stack is kind of like an array. But a stack doesn't have any index. You can only execute the last/recent element or delete the last/recent element. So on a stack, you can only perform two operations push
and pop
.
Let's look at a piece of code:
function one(){
two();
}
function two() {
three();
}
function three() {
console.trace(“Lets Call The Stack”);
}
one();
So the stack flow will be like this:
Stack = [ one, two, three ]
Once three()
is executed, then the stack will look like this:
Stack = [ one, two ];
After two()
is executed then it becomes like this:
Stack = [ one ]
And lastly when one()
is executed then the event loop which simply means looping through the stack and executing the last block of code/function is stopped.
Now, in case of p5.js/Processing, the setup()
function is called and executed but the draw()
function keeps being added to the stack and the event loop keeps looping through the stack and executed the last block/function which is, in this case, draw()
.
Another thing is you can't declare setup()
or draw()
inside another function. The have to declared independently and separately. I had to waste a lot of trying to do this, but couldn't find anything.