2

my question is why myFunction2 is triggered immediately, how javascript works like this? thanks.

<!--when passing "myFunction1" without (), myFunction1 is triggered after 3 seconds as expected-->
<button onclick="setTimeout(myFunction1, 3000);">Try it 1</button>

<script>
function myFunction1() {
    alert('Hello');
}
</script>

<!--when passing "myFunction2" with (), myFunction1 is triggered right away as clicking the button-->
<button onclick="setTimeout(myFunction2(), 3000);">Try it 2</button>

<script>
function myFunction2() {
    alert('Hello');
} 
</script>
Qiao Li
  • 189
  • 1
  • 1
  • 10
  • 1
    because you're calling it here: `setTimeout(myFunction2(), 3000)`. The function name is `myFunction2`; writing `myFunction2()` will call the function, not just reference it. To pass the function reference to `setTimeout`, just do `setTimeout(myFunction2, 3000)` – Hamms Apr 18 '17 at 00:13
  • [**Here**](http://stackoverflow.com/a/43436818/6647153) is an answer to a similar but not the same question. (look for **Callback:** section)! `addEventListener` and `setTimeout` follow the same structure! – ibrahim mahrir Apr 18 '17 at 00:15
  • so myFunction2 was not passed as the onclick event handler, is this correct? – Qiao Li Apr 18 '17 at 00:19
  • then what if myFunction2 accept and parameter "x". and i need to pass the function to with a value. something like this (but how to make it wait for 3 seconds?): – Qiao Li Apr 18 '17 at 00:25
  • @QiaoLi That is correct, myFunction2 was not passed as the onclick event handler, instead whatever was returned from myFunction2 (in this case, nothing) was passed to the event handler – Joe Lissner Apr 18 '17 at 00:26
  • If myFunction2 needs to accept an argument, then you can do myFunction2(x) { return function() {alert(x)} } – Joe Lissner Apr 18 '17 at 00:26
  • Thanks for your help guys. it works now. That was really confusing to me. – Qiao Li Apr 18 '17 at 00:30
  • Possible duplicate of [setTimeout calls function immediately instead of after delay](http://stackoverflow.com/questions/27643714/settimeout-calls-function-immediately-instead-of-after-delay) – Tibrogargan Apr 28 '17 at 21:50

0 Answers0