Simply put...
why does
setTimeout(\'playNote(\'+currentaudio.id+\', \'+noteTime+\')\', delay);
work perfectly, calling the function
It may help to understand when javascript executes code, and when it waits to execute something:
let foo2 = function foo(bar=baz()){ console.log(bar); return bar()}
=>
syntax, and you get similar (but not identical) results.foo2
baz
nor bar
, no values looked up, etc. However, the syntax has been checked inside the function.foo
or foo2
to setTimeout
then after the timeout, it would call the function, the same as if you did foo()
. (notice that no args are passed to foo
. This is because setTimeout
doesn't by default pass arguments, although it can, but those arguments get evaluated before the timeout expires, not when it expires.)bar
is evaluated. (This would not have happened if we passed an argument)bar
, first javascript looks for a variable named baz
. If it finds one, it then tries to call it as a function. If that works, it saves the return value to bar
.bar
and then calls console.log with the result. This does not call bar. However, if it was instead called as bar()
, then bar
would run first, and then the return value of bar()
would be passed to console.log
instead. Notice that javascript gets the values of the arguments to a function it is calling before it calls the function, and even before it looks up the function to see if it exists and is indeed a function.bar
, and then it tries to call it as a function. If that works, the value is returned as the result of foo()
So, function bodies and default arguments are not called immediately, but everything else is. Similarly, if you do a function call (i.e. ()
), then that function is executed immediately as well. However, you aren't required to call a function. Leaving off the parentheses will allow you to pass that function around and call it later. The downside of that, though, is that you can't specify the arguments you want the function to be called with. Also, javascript does everything inside the function parentheses before it calls the function or looks up the variable the function is stored in.