Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTimeout in javascript within function [duplicate]

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..

like image 794
Vinay Avatar asked Sep 18 '26 05:09

Vinay


2 Answers

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

setTimeout(func1,10000);
like image 70
Andy E Avatar answered Sep 19 '26 19:09

Andy E


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) 
}
like image 22
jahroy Avatar answered Sep 19 '26 19:09

jahroy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!