2

I trying to pass a variable down one level into a setInterval function my code looks something like this:

function file_copy_progress(directory){
 console.log("stage 1 " + directory);
 setInterval(function(directory){
 console.log("stage 2 " + directory);
 }, 1000);
}

then I call it like this:

file_copy_progress("/home/user/tmp/test");

The result in the console is:

stage 1 /home/user/tmp/test
stage 2 undefined
stage 2 undefined
stage 2 undefined
...

How would I pass the directory variable down one more level to be available in the setIntervall function?

asked Feb 24, 2013 at 17:53

1 Answer 1

7

Just remove the formal parameter directory in your inner function

function file_copy_progress(directory){
 console.log("stage 1 " + directory);
 setInterval(function(){
 console.log("stage 2 " + directory);
 }, 1000);
}

The directory parameter of the outer function is captured in the closure of the inner function. Therefore you don't need to pass it as a parameter to the inner function. On the contrary, if you have the formal parameter to the inner function, it hides the captured variable and makes it inaccessible to the inner function.

answered Feb 24, 2013 at 17:55
Sign up to request clarification or add additional context in comments.

5 Comments

Can you add a line or two to explain why this solves the problem?
I get it now too, but why does passing it gain eliminate the variable?
@JasonBurgett variable shadowing.
@Chris I tried to explain it a bit. I hope it is clearer now. If it is not, let me know.
Yup - was just looking for the bit more for doling out the +1 :)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.