Reputation: 2923
I'm having great trouble understanding the first argument for setTimeout
and how the delay argument effects it.
The way I understand setTimeout
is:
setTimeout(foo, don't even think about foo until x miliseconds has passed)
But if we consider this code:
<div id="mine"></div>
<script type="text/javascript">
function go(){
var myDiv = document.getElementById("mine");
myDiv.innerHTML = "Hello World";
}
setTimeout(go(), 2000)
</script>
go
is run right away without waiting 2 seconds.
As many before me have pointed out, setTimeout(go(), 2000)
is asking for the return value when I actually want setTimeout(go, 2000)
.
Frankly, I don't understand the difference other than "one works, and one doesn't." Why doesn't the former also respect the delay argument?
Upvotes: 0
Views: 116
Reputation: 140
var go = function () {
console.log('GO GO GO!');
};
setTimeout(go, 2000);
Upvotes: -3
Reputation: 94101
A function in JavaScript is an object. go
is the function object, go()
executes the go
function and returns its value. setTimeout
expects a function, thus go
, not go()
.
function go(){
return 'hello';
}
console.log(go); //=> function go(){}, a function object
console.log(go()); //=> 'hello', a string returned by the function `go`
Upvotes: 7