Calling functions with setTimeout()

后端 未结 6 1561
谎友^
谎友^ 2020-11-21 06:49

Simply put...

why does

setTimeout(\'playNote(\'+currentaudio.id+\', \'+noteTime+\')\', delay);

work perfectly, calling the function

6条回答
  •  半阙折子戏
    2020-11-21 07:24

    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()}

    • The first thing javascript executes is the function constructor, and creates a function object. You can use either the function keyword syntax or the => syntax, and you get similar (but not identical) results.
    • The function just created is then assigned to the variable foo2
    • At this point nothing else has been run: no other functions called (neither baz nor bar, no values looked up, etc. However, the syntax has been checked inside the function.
    • If you were to pass 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.)
    • After foo is called, default arguments are evaluated. Since we called foo without passing arguments, the default for bar is evaluated. (This would not have happened if we passed an argument)
    • While evaluating the default argument for 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.
    • Now the main body of the function is evaluated:
    • Javascript looks up the variable 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.
    • Javascript again looks up 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.

提交回复
热议问题