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?
1 Answer 1
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.