Home >Web Front-end >JS Tutorial >Why Does My JavaScript Code Fail When Using `setTimeout` With Function Expressions?
In JavaScript, code execution involves two phases: compilation and evaluation. The first example fails because of a fundamental misunderstanding between function declarations and expressions regarding these phases.
Function declarations use the function keyword and follow the syntax:
function name (arguments) {code}
Function expressions, on the other hand, are written in expression context and follow the same syntax as declarations, except that they are wrapped in parentheses. Expressions are processed during execution, not compilation.
Example 1:
(function() { setTimeout(someFunction1, 10); var someFunction1 = function() { alert('here1'); }; })();
Compilation: SomeFunction1 is defined as undefined.
Execution: setTimeout is called with the undefined value of someFunction1.
Example 2:
(function() { setTimeout(someFunction2, 10); function someFunction2() { alert('here2'); } })();
Compilation: SomeFunction2 is declared as a function..
Execution: setTimeout is called with the compiled someFunction2 function.
Example 3:
(function() { setTimeout(function() { someFunction3(); }, 10); var someFunction3 = function() { alert('here3'); }; })();
Compilation: SomeFunction3 is initially defined as undefined.
Execution: An anonymous function is passed to setTimeout, creating a closure to someFunction3. Later, someFunction3 is assigned a function, which overrides its undefined value.
Example 4:
(function() { setTimeout(function() { someFunction4(); }, 10); function someFunction4() { alert('here4'); } })();
Similar to Example 2, someFunction4 is declared before being passed to setTimeout.
The first example fails because someFunction1 is not declared before being passed to setTimeout during compilation. Function expressions must be evaluated during execution, after declarations have been processed. Therefore, the order of expressions is crucial when using function expressions, especially when passed to asynchronous functions like setTimeout.
The above is the detailed content of Why Does My JavaScript Code Fail When Using `setTimeout` With Function Expressions?. For more information, please follow other related articles on the PHP Chinese website!