I'm currently looking at a Javascript tutorial , which has a line of code that I don't fully understand.
The following code is so that after 3 seconds the browser releases a alert
with the corresponding message.
function muestraMensaje() {
alert("Han transcurrido 3 segundos desde que me programaron");
}
setTimeout(muestraMensaje, 3000); //llama a la función sin paréntesis
I made the same code without looking at it again and it worked incorrectly , since it did not wait for the 3 seconds and when the page was loaded again it immediately showed the message.
Looking at my code, I realized that unlike the tutorial, I was calling the function with parentheses:
setTimeout(muestraMensaje(), 3000);
And when removing them and putting the code as it is in the tutorial, it works correctly, it waits the corresponding seconds and then it shows the message.
Why with parentheses does it perform the request immediately and not wait the 3 seconds, like it does when I take out the parentheses?
EDIT: While in the tutorial, it expresses the following:
As usual, when indicating the reference to the function, the parentheses are not included, since otherwise, the function is executed at the same moment in which the execution interval is established.
I would like to know why this happens anyway. Since if it were a function that received parameters it would work incorrectly.