1

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?

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

+1, but closure or anonymous function makes it sound like they are the same thing.
@alex Can't quite find wording I like for that, but for basic purposes anonymous functions and closures are closely enough related.
so obvious when I quick read the article :) I didn't know they kept the local variables even of scope. I learned something new! I could even implement the first solution I had in mind from the beginning :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.