code_0:
(calling foo
without parentheses)
function foo(){
console.log('hello world');
}
setTimeout(foo, 2000);
This is how code_0
was executed:
start -> wait for 2 seconds -> 'hello world' displayed -> end
code_1:
(calling foo
with parentheses)
function foo(){
console.log('hello world');
}
setTimeout(foo(), 2000);
And this is how code_1
was executed:
start -> 'hello world' displayed immediately -> wait for 2 seconds -> end
Why would the program perform so differently when I called the function with parentheses? What is the underlying mechanism?
Sorry if this question is too trivial. But I could't find an explanation on any javascript tutorial for beginners.