2

I have two functions like below,

func1 = function(){
    console.log("func1 is called"); 
}

func2 = function(){
    console.log("func2 is called");
    setTimeout(func1(),10000) 
}

When I make a call like func2(). I get the output but not the expected one.As you can see I have used a setTimeout() in func2 and I expect some delay as specified before func1 gets executed.

But no delay is observed both the lines gets printed to console at the same time. What am I doing wrong here or am I missing anything? Please help..

Vinay
  • 6,891
  • 4
  • 32
  • 50

3 Answers3

9

When referencing a function, you need to leave off the brackets.

setTimeout(func1,10000);
Andy E
  • 338,112
  • 86
  • 474
  • 445
3

Remove the parentheses after func1 in your call to setTimeout.

The setTimeout function expects a function reference.

Your code passes the result of invoking func1 to setTimeout() after printing an alert.

When parentheses follow the name of a function, they cause the function to be invoked.

func1 = function () {
    alert('func1 is called');
}

func2 = function(){
    console.log("func2 is called");
    // Invoke func1 and pass the return value (which is undefined) to setTimeout.  
    // An alert will be displayed immediately when func1 is invoked.
    setTimeout(func1(),10000) 
}

func2 = function(){
    console.log("func2 is called");
    // Pass a reference to func1 to setTimeout to be invoked later.
    setTimeout(func1,10000) 
}
jahroy
  • 22,322
  • 9
  • 59
  • 108
2

You could also specify an anonymous function :

setTimeout(function(){func1();},10000);
sdespont
  • 13,915
  • 9
  • 56
  • 97
  • 2
    This is not needed, leaving the parentheses does the trick aswell. And is more readable then a anonymous function. – RvdK Mar 29 '13 at 09:05
  • Yes, you are both right, but it is also a valid solution. – sdespont Mar 29 '13 at 09:06
  • 2
    But still a redundant one in this case; there's no gain unless you want to pass arguments to the function. – Andy E Mar 29 '13 at 09:10
  • @AndyE : Offer several different solutions to the asker seems to be a good thing for me. – sdespont Mar 29 '13 at 09:13
  • 1
    @sdespont: I don't mean to offend, and in certain scenarios I may agree with you, but your answer promotes a somewhat poor practice of adding unnecessary bulk and inefficiencies to code. – Andy E Mar 29 '13 at 09:22