1

Here is my Javascript function;

var searchbox=function(){
    var _expandbox=function(count){
    };

    var _events=function(){
        setTimeout(_expandbox,3000);
    }

    var _init=function(){
        _events();
    };

    return {
        init: _init
    };
}();

$(document).ready(function(){
    searchbox.init();
});

Here the problem is if I call function like setTimeout(_expandbox(4),3000) it won't work.So plese help me how to add parameter in function.

Dhwani sanghvi
  • 475
  • 4
  • 14
  • It's like the first hit on Google with the frase *"setTimeout not working"* -> http://stackoverflow.com/questions/20890943/javascript-settimeout-not-working – adeneo Oct 22 '15 at 06:10
  • I am not talking about why setTimeout is not working.My qustion is about how to pass parameter in function in modular javascript pattern. – Dhwani sanghvi Oct 22 '15 at 06:15
  • Doesn't matter what pattern you're using, calling a function rather than referencing it in `setTimeout` is your issue, and it's a duplicate of several other questions, and the answer below is the same as those duplicates. – adeneo Oct 22 '15 at 06:21
  • Lets look at a simpler example: `foo(bar())`. This will *first* call `bar` and pass its return value to `foo`. That's how pretty much every common programming language works. The same happens with `setTimeout(_expandbox(4),3000)`. It calls `_expandbox(4)` and passes the return value (which is `undefined`) to `setTimeout`. I.e. it's equivalent to `setTimeout(undefined, 3000)`. However, `setTimeout` expects a function that it can call in the future, not `undefined`. – Felix Kling Oct 22 '15 at 06:25

1 Answers1

1

Try wrapping it in an anonymous function:

setTimeout(function() { _expandbox(4); }, 3000);
Griffith
  • 3,061
  • 1
  • 13
  • 30
  • Thank you.Actually I want to know why setTimeout(_expandbox(4),3000); can't give correct answer. – Dhwani sanghvi Oct 22 '15 at 06:12
  • The first parameter for setTimeout is a function, `setTimeout(_expandbox(4),3000);` is passing the return value of `_expandbox(4)` as parameter, which is invalid. – Griffith Oct 22 '15 at 06:15
  • 1
    @Dhwani91 - whenever you add the parentheses you call the function immediately and pass the returned value, which in this case is `undefined` to `setTimeout`. There's a difference in **calling** a function with the parentheses, and **referencing** a function with it's name only, to be invoked later. – adeneo Oct 22 '15 at 06:22
  • Thanks.now it clears my doubt,@adeneo – Dhwani sanghvi Oct 22 '15 at 06:25