setTimeout(myFunction, 5000); vs setTimeout(myFunction(), 5000);

后端 未结 3 825
忘了有多久
忘了有多久 2021-01-21 13:27

I was playing around with the \"setTimeout\" function. This code runs like expected:

function myFunction() {
    console.log(\'test\');
    setTimeout(myFunction         


        
相关标签:
3条回答
  • 2021-01-21 13:53

    myFunction() calls the function immediately and passes its return value to setTimeout to be called later (except its return value is undefined, which isn't a function (or a string), so that is pointless).

    0 讨论(0)
  • 2021-01-21 14:04

    That is because by including the parentheses you're actually executing the function and passing its result to setTimeout.

    0 讨论(0)
  • 2021-01-21 14:09

    setTimeout(myFunction(), 1000); means that your pass result returned by myFunction() as the 1st argument of setTimeout. myFunction returns nothing, so setTimeout(myFunction(), 1000); is the same as setTimeout(undefined, 1000);

    0 讨论(0)
提交回复
热议问题