Max Kielland
Max Kielland

Reputation: 5841

Javascript - Pass a function with arguments as an argument

I'm cleaning up some script errors and have a delicate dilemma.

Consider this line of code:

Session.Timer = window.setTimeout("TimeoutHandler(Session)", 1000);

This will not work because when the Timeout tries to execute TimeoutHandler(Session) it will not know what the Session variable is (out of scope).

Is there a way to get the Session "value" translated to a string or number so it will be executed correctly?

Upvotes: 1

Views: 601

Answers (1)

cobbal
cobbal

Reputation: 70713

Use a closure (using an anonymous function) instead of a string, it will keep a reference to Session for you.

Session.Timer = window.setTimeout(function() { TimeoutHandler(Session); }, 1000);

If you're unfamiliar with closures, here's a brief introduction.

Upvotes: 6

Related Questions