I'm new to JavaScript and I have a ptoblem with a code that looks like this:
function job1() {
    var subText1="";
    var subText2="";
    var text="";
    var vocabulary = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz0123456789";
    // Use the delay function to create a full text in 20 * 150 milliseconds
    var i = 0, 
    action = function() {
                var temp = vocabulary.charAt(Math.floor(Math.random() * vocabulary.length));
                text+= temp;
                document.write(text + "<br>");
                i++;
                if (i < 20) {
                            setTimeout(action, 150);
                } else {
                    // The first subText is from position 0 until some random number random between 0 and the text length
                    subText1 = text.slice(0, Math.floor(Math.random() * text.length));
                    // The second subText is from where the first subText ends until the last character form the text input
                    subText2 = text.slice(subText1.length, text.length);
                    // output of the subText1 and the subText2 for the first time
                    document.write("subText1: " + subText1 + "<br>");
                    document.write("subText2: " + subText2 + "<br>");
                    document.write("text: " + text + "<br>");
                }
            };
        setTimeout(action, 0);
        // output of the subText1 and the subText2 once more
        document.write("subText1: " + subText1 + "<br>");
        document.write("subText2: " + subText2 + "<br>");
        // NextJob: job2, job3
        // job dependency
        var nextJob = "job2, job3";
        var prevJob = "null";
        // results
        return { 
        subText1_RT : subText1,
        subText2_RT : subText2
        };
}
my problem is that I need to  to get the subText1 and the subText2 from the action = function().... section into this section:
return { 
   subText1_RT : subText1,
   subText2_RT : subText2
};
But the subText1 and the subText2 variables are empty.
Here is a fiddle to the code: http://jsfiddle.net/TalGoz/4tgc372e/
It looks like all the parts of the job1() function are executed before the action = function() part. It is very important to get it working like this as function inside a function, I can’t separate the functions for the purpose of my goal.
I hope someone here can help me see the problem and solve it.
 
    