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.
To answer this let's evaluate how it works
setTimeout
, itsetTimeout
receives 2 parameters (1) a function to execute and (2) the time you want it to wait to execute that function.In this example it is sent the function that you want to be executed and the timeout that you want to be executed and that is why it works correctly
and in this other example you no longer send a function as the first parameter but you send the result of the function, what the code will do is execute the function because you are executing it yourself since that is what the parentheses do, in this case the function does not return nothing but if it returned something that is what would be sent as a parameter to
setTimeout
I will give you an example to make it more sense, to demonstrate more easily
The parentheses "execute" the function, in the example above.
In conclusion, with the parentheses you are immediately executing the function, and without the parentheses you are passing a "reference" to the function to be executed.