Reputation: 89
In The following code i am using setTimeout to call the foo
function foo() {
console.log('2000 milliseconds have passed since this demo started');
}
setTimeout(foo, 2000);
According to my knowledge if we won't use the parenthesis the code will just refer to the function as a pointer how the function is being an executed called here without parenthesis
Upvotes: 0
Views: 62
Reputation: 304
Take an example
function f() {
return 10;
}
var a = f();
var b = f;
Here a contains 10 while b will contain a reference to function f. You can call the function on b using
var c = b(); // c contains 10
In a similar way settimeout works. If you call the function with parentheses it will get called immediately. While we dont use parentheses so the settimeout function will have a reference and call it after the specified time.
Upvotes: 1
Reputation: 943214
Take this example for comparison:
function myFunction(callback) {
callback();
}
function foo() {
console.log('The foo function has been called');
}
myFunction(foo);
The function you pass as an argument is called by code inside myFunction
.
setTimeout
works in a similar way: You just aren't looking at its source code because it isn't code you wrote yourself. It comes with the browser.
Upvotes: 1