MarioDu
MarioDu

Reputation: 135

How to pass arguments to a function in setTimeout

I have the following code:

function fn($){
  return function(){
    innerFn = function(){
      setTimeout(show, 1000);
    };

    show = function(){
      $.alert("TEST");
    }
  }
}

But, after one second, when the function show is run, it says $ is undefined. How do I resolve this issue?

Upvotes: 0

Views: 128

Answers (3)

ZER0
ZER0

Reputation: 25322

Your code makes no any sense, because nothing is called:

function fn($){
  return function(){
    innerFn = function(){
      setTimeout(show, 1000);
    };

    show = function(){
      $.alert("TEST");
    }
  }
}

Let's say I'm calling fn passing window, then a function is returned, that I can executed. But because this function is containing only function declaration - you also forget var so you pollute the global scope, that is bad - nothing is happen.

You'll need at least one function call inside, like:

function fn($){
  return function(){
    var innerFn = function(){
      setTimeout(show, 1000);
    };

    var show = function(){
      $.alert("TEST");
    }

    innerFn();
  }
}

fn(window)();

And that will works. However, it's definitely redundant. You can just have:

function fn($){
  return function(){
    function show(){
      $.alert("TEST");
    }

    setTimeout(show, 1000);
  }
}

To obtain the same result. However, if you're goal is just bound an argument to setTimeout, you can use bind. You could use the 3rd parameter of setTimeout as the documentation says, but it seems not supported in IE for legacy reason.

So, an example with bind will looks like:

function show() {
    this.alert('test');
}

setTimeout(show.bind(window), 1000);

Notice also that window is the global object by default, so usually you do not have to do that, just alert is enough. However, I suppose this is not your actual code, but just a mere test, as the alert's string says.

If you prefer having window as first parameter instead, and you're not interested in the context object this, you can do something like:

function show($) {
    $.alert('test');
}

setTimeout(show.bind(null, window), 1000);

Upvotes: 1

Evan Borden
Evan Borden

Reputation: 301

There are a number of things at play here. The most important being that your setTimeout never gets called, since innerFn never gets called. This should do the trick.

function fn($){
  return function(){
    setTimeout(function(){
      $.alert("TEST");
    }, 1000);
  }
}

fn(window)(); //triggers your alert after 1000ms

Upvotes: 1

Royi Namir
Royi Namir

Reputation: 148524

how to pass arguments to a function in setTimeout

setTimeout has a built in mechanism for adding params

var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);

use it.

If you're going to use this - you should be careful. but that's another question.

Upvotes: 2

Related Questions